Creating SQL Server Stored Procedures in C#
In this article we will look at creating stored procedures using C#. We will query the database to ensure that the procedure does not exist before we add it to the data dictionary.
This tutorial follows on from a previous tutorial where we looked at how to call stored procedures from C#
We need to create a connection to the SQL Server and execute a command that will interrogate the stored procedures for the database and store the results in the SqlDataReader. If the DataReader does not contain any rows then the stored procedure does not exist and it is safe to create it. If it does exist you may wish to update or delete it.
- SqlConnection MyConnection =new SqlConnection("server=(local);database=pubs;UID=myUser;PWD=myPassword;");
- SqlCommand MyCommand =new SqlCommand("select * from sysobjects where id = object_id(N'GetAuthorsByLastName') and OBJECTPROPERTY(id, N'IsProcedure') = 1", MyConnection);
- MyCommand.CommandType= CommandType.Text;
- SqlDataReader MyDataReader = MyCommand.ExecuteReader();
- // If any rows are returned, the stored procedure that you are trying
- // to create already exists. Therefore, try to create the stored procedure
- // only if it does not exist.
- MyCommand.CommandText="create procedure GetAuthorsByLastName(@au_lname varchar(40), select * from authors where au_lname like @au_lname; select @RowCount=@@ROWCOUNT";
- catch(Exception ex)
More Tutorials in Active Data Objects (ADO.Net)
- What are Active Data Objects?
- Connecting to a SQL Server Database with C#
- Consuming Data in Windows Forms C# Applications
- Using ADO.Net Controls in ASP.Net Pages
- Modifying Data and Updating Databases with C#
- Connecting to MySql Databases with C# / ASP.Net
- Reading Excel Spreadsheets with C# ADO.Net
- Creating SQL Server Stored Procedures in C# ⇦ You Are here
- Calling SQL Server Stored Procedures from C#
- Importing and Exporting XML from a DataSet