DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Basics Of Stored Procedures In .NET

Basics Of Stored Procedures In .NET

Denzel D. user avatar by
Denzel D.
·
Oct. 11, 12 · Interview
Like (0)
Save
Tweet
Share
13.70K Views

Join the DZone community and get the full member experience.

Join For Free

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) 

AS 

INSERT INTO Users 

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 
{ 
UpdateOnly, 
WithReturn 
} 
SqlDataReader ExecuteProcedure(string connectionString, string procedureName, Dictionary<string,string> parameters,ProcedureType pType) 
{ 
SqlDataReader reader = null; 
SqlConnection sqlConn; 
SqlCommand sqlCmd; 
try 
{ 
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) 
{ 
sqlConn.Open(); 
sqlCmd.ExecuteNonQuery(); 
sqlConn.Close(); 
} 
else 
{ 
sqlConn.Open(); 
reader = sqlCmd.ExecuteReader(); 
} 
} 
catch (Exception ex) 
{ 
System.Diagnostics.Debug.Print( 
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.

Database

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Why Open Source Is Much More Than Just a Free Tier
  • SAST: How Code Analysis Tools Look for Security Flaws
  • 3 Ways That You Can Operate Record Beyond DTO [Video]
  • Why You Should Automate Code Reviews

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: