Saturday, May 22, 2010

Using sql server how to call stored procedure for insert,delete and update in c#.net with asp.net?

Here is a good article on this. Once you have created the procedure in SQL you need to basically create the connection, setup the command and type, assign you input/output params to the command (if any, this would be used to pass values for your where clause when updating for example), open the connection, then excecute your command. Here is the code that does that. The full article can be found in the link below.





SqlConnection cnPubs = new SqlConnection


("server=localhost;integrated security=true;" + "database=pubs");





Next, create a SqlCommand object and set the appropriate properties needed to execute the up_AuthorBookCount stored procedure created earlier.





SqlCommand cmdAuthors = new SqlCommand("up_AuthorBookCount", cnPubs);


cmdAuthors.CommandType = CommandType.StoredProcedure;





Using the Add method of the SqlCommands Parameter collection add an input parameter that takes the AuthorId value passed in by the caller. Also add an output parameter that will store the value passed back by the stored procedure. The names and data types of the parameters must mach those defined in the stored procedure.





cmdAuthors.Parameters.Add("@au_id", SqlDbType.NVarChar, 11);


cmdAuthors.Parameters["@au_id"].Value = AuthorID;


cmdAuthors.Parameters.Add("@Count", SqlDbType.Int);


cmdAuthors.Parameters["@Count"].Direct... = ParameterDirection.Output;





Open the connection to the database and call the ExecuteNonQuerry method of the command object. Once the stored procedure is executed, the value of the output parameter is held in a local variable, which is in turn passed back to the client. Dont forget to close the connection after executing the stored procedure.





cnPubs.Open();


int iCount;


cmdAuthors.ExecuteNonQuery();


iCount = (int)cmdAuthors.Parameters["@Count"].Val...


cnPubs.Close();


return iCount;

Using sql server how to call stored procedure for insert,delete and update in c#.net with asp.net?
first compile your class and then use it in namespace in current page


No comments:

Post a Comment