Over a million developers have joined DZone.

Basics Of Stored Procedures In .NET

DZone's Guide to

Basics Of Stored Procedures In .NET

· Database Zone
Free Resource

Download the Guide to Open Source Database Selection: MySQL vs. MariaDB and see how the side-by-side comparison of must-have features will ease the journey. Brought to you in partnership with MariaDB.

Using stored procedures instead of writing SQL queries manually is a good thing to do in pretty much every application that involves SQL databases.

In C#, to execute a stored procedure, a developer needs to initialize an instance of SqlConnection, set the connection string, create an instance of SqlCommand, add the parameters, set the type of the command to StoredProcedure and use ExecuteNonQuery() to execute it. Using this every single time for every other stored procedure that needs to be called can involve more code that a developer probably wants to see in a function.

Therefore, I was working on a function that would unify all this code in one place, and whenever needed, it can be called in one line of code.

Suppose I have a database on my SQL Server called MySystem. There is also a table, called Users. Now, I also a have a stored procedure to simplify the process of adding new users to the system:

PROCEDURE [dbo].[AddUser] (@userID CHAR(36), @username CHAR(25), @password CHAR(25), @fullname CHAR(60), @role INT) 



VALUES (@userID, @username, @password, @role, @fullname) 

Don’t get confused by such a long userID – a GUID is used as a user identifier in my case.

Here is my function that will execute stored procedures in C#:

enum ProcedureType 
SqlDataReader ExecuteProcedure(string connectionString, string procedureName, Dictionary<string,string> parameters,ProcedureType pType) 
SqlDataReader reader = null; 
SqlConnection sqlConn; 
SqlCommand sqlCmd; 
sqlConn = new SqlConnection(connectionString); 
sqlCmd = new SqlCommand(procedureName, sqlConn); 
sqlCmd.CommandType = CommandType.StoredProcedure; 
if (parameters != null) 
foreach (string parameter in parameters.Keys) 
sqlCmd.Parameters.AddWithValue(parameter, parameters[parameter]); 
if (pType == ProcedureType.UpdateOnly) 
reader = sqlCmd.ExecuteReader(); 
catch (Exception ex) 
string.Format("An exception occured when executing the {0} stored procedure. {1}", 
procedureName, ex.Message)); 

return reader; 

Its parameters are pretty much self explanatory – it gets the connection string, the name of the stored procedure, the list of parameters to be passed to the procedure and the type of the procedure. UpdateOnly means that the stored procedure is executed and there is no value that needs to be read by the end user.  WithReturn means that there are results returned (in case with SELECT statements, for example). If a value is not returned, SqlDataReader is null. Otherwise, it contains the response data. Mention the fact that the list of parameters is represented as Dictionary<string,string>. This is because parameters to the procedure are passed as value pairs – the parameter name and the value of the parameter.

Here is a piece of sample code that shows how to use the above mentioned function applied to my sample database (should be places in an event handler to be triggered):

string connectStr = @"server=DEN-PC\SQLEXPRESS;database=MySystem;uid=admin;pwd=pass"; 
Dictionary<string, string> parameters = new Dictionary<string, string>(); 
parameters.Add("@userID", "4d36e978-e325-11ce-bfc1-08002be10311"); 
parameters.Add("@username", "somename"); 
parameters.Add("@password", "passHash"); 
parameters.Add("@role", "1"); 
parameters.Add("@fullname", "Someone Pass"); 
SqlDataReader reader = ExecuteProcedure(connectStr, "AddUser", parameters, ProcedureType.WithReturn); 

Pretty simple, and can be easily reused when needed.

NOTE: You need to declare the System.Data and System.Data.SqlClient namespaces before using the function.

Interested in reducing database costs by moving from Oracle Enterprise to open source subscription?  Read the total cost of ownership (TCO) analysis. Brought to you in partnership with MariaDB.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}