Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Visual C# » Using Stored Procedures with ASP.NET

Using Stored Procedures with ASP.NET

This article helps you to create a stored procedure on SQL Server and tells you how to use them in your asp.net applications.

Page Views : 201370
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

Stored procedures (sprocs) are generally an ordered series of Transact-SQL statements bundled into a single logical unit. They allow for variables and parameters, as well as selection and looping constructs. A key point is that sprocs are stored in the database rather than in a separate file.

Advantages over simply sending individual statements to the server include:

  1. Referred to using short names rather than a long string of text; therefore, less network traffiic is required to run the code within the sproc.
  2. Pre-optimized and precompiled, so they save an incremental amount of time with each sproc call/execution.
  3. Encapsulate a process for added security or to simply hide the complexity of the database.
  4. Can be called from other sprocs, making them reusable and reducing code size.

Parameterization

A stored procedure gives us some procedural capability, and also gives us a performance boost by using mainly two types of parameters:

  • Input parameters
  • Output parameters

From outside the sproc, parameters can be passed in either by position or reference.

Declaring Parameters

  1. The name
  2. The datatype
  3. The default value
  4. The direction

The syntax is :                     

@parameter_name [AS] datatype [= default|NULL] [VARYING] [OUTPUT|OUT]

Let's now create a stored procedure named "Submitrecord".

First open Microsoft SQL Server -> Enterprise Manager, then navigate to the database in which you want to create the stored procedure and select New Stored Procedure.



See the below Stored Procedure Properties for what to enter, then click OK.



Now create an application named Store Procedure in .net to use the above sprocs.

Stored Procedure.aspx page code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat="server">
<title>Store Procedure</title>
</
head>
<
body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="ID"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /><br />
<asp:Label ID="Label2" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br /><br />
<asp:Label ID="Label3" runat="server" Text="Confirm Password"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br /><br />
<asp:Label ID="Label4" runat="server" Text="Email ID"></asp:Label>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox><br /><br /><br />
<asp:Button ID="Button1" runat="server" Text="Submit Record" OnClick="Button1_Click" />
</div>
</form>
</
body>
</
html>

Stored Procedure.aspx.cs page code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    
DataSet ds = new DataSet();
    
SqlConnection con;
     //Here we declare the parameter which we have to use in our application
    
SqlCommand cmd = new SqlCommand();
    
SqlParameter sp1 = new SqlParameter();
    
SqlParameter sp2 = new SqlParameter();
    
SqlParameter sp3 = new SqlParameter();
    
SqlParameter sp4 = new SqlParameter();

protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)

{
     con =
new SqlConnection("server=(local); database= gaurav;uid=sa;pwd=");
     cmd.Parameters.Add(
"@ID", SqlDbType.VarChar).Value = TextBox1.Text;
     cmd.Parameters.Add(
"@Password", SqlDbType.VarChar).Value = TextBox2.Text;
     cmd.Parameters.Add(
"@ConfirmPassword", SqlDbType.VarChar).Value = TextBox3.Text;
     cmd.Parameters.Add(
"@EmailID", SqlDbType.VarChar).Value = TextBox4.Text;
     cmd =
new SqlCommand("submitrecord", con);
     cmd.CommandType =
CommandType.StoredProcedure;
     con.Open();
     cmd.ExecuteNonQuery();
     con.Close();
}
}

When we run the application, the window will look like this:



After clicking the submit button the data is appended to the database as seen below in the SQL Server table record:
 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Gaurav Tomar
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Store Procedure with Asp.Net by Manas On December 13, 2007
The way you described it's gr8...It's very necessary for a fresher........Thanks Manas
Reply | Email | Modify 
Dude by Pravin On December 21, 2007
Great work buddy, thanks for us
Reply | Email | Modify 
another way by X On December 26, 2007
sql procedure is some letters , you can execute it on sql ide like "exec proc_name , arg1,...",then , we can execute procedure in c# like this way, SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandText = "exec proc_name , arg1,..."; but this way has a defect that is can not use output argument
Reply | Email | Modify 
A Doubt On C#.Net by posubabu On January 1, 2008
Dear Sir....... Iam Working on DetailsView. In That Details View How TOo Edit The Data by Using Commmand field /Hyperlink Field And Another Doubt Is In My Project Is Each ProjectLeadre Has Create Thier Own NewProject And Editing That Project Details If there Is Tasks On The Project. But In My Prject Is Every ProjectLeader Has Seen Another Project Leader Details.and Tasks.. But The Main Thing Is Every Project Leader Has Own Details And Tasks.Onlyyyyyyyyy.... In That Siuations Another Projects Details oor not Visible ........Please Kindly Replied ABout My Question? Sir....... Thanking You Sir.... Your's Sincerely Posubabu.K Trainee Consultant, IBLESOFT PVT LTD
Reply | Email | Modify 
C#.net by posubabu On January 1, 2008
How to Editing Data in DetailsView
Reply | Email | Modify 
sproc by deep On January 2, 2008
thanx it is very useful for fresher
Reply | Email | Modify 
sproc by deep On January 2, 2008
thanx it is very useful for fresher
Reply | Email | Modify 
sproc by deep On January 2, 2008
thanx it is very useful for fresher
Reply | Email | Modify 
10x alot :) by Zero Energy On February 3, 2008
U R da Man Dude ;) Hope Always Better
Reply | Email | Modify 
ambrish by ambrish On February 8, 2008
hi gaurav i ambrish i have one problem how we can fill more than two table recored in gridview using corcer give complete code in asp.net with c#.net ok Thanks
Reply | Email | Modify 
Modification(Stored Procedure.aspx) by Sheetal On January 25, 2009
Modications to be done to Stored Procedure.aspx ------
using System; using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
 using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
  { }
protected void Button1_Click(object sender, EventArgs e)
 {
 SqlConnection con = new SqlConnection("server=(local); database= Sample;uid=sa;pwd=pass");
 SqlCommand cmd = new SqlCommand("submitrecord", con); cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = TextBox1.Text; cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = TextBox2.Text; cmd.Parameters.Add("@ConfirmPassword", SqlDbType.VarChar).Value=TextBox3.Text;
cmd.Parameters.Add("@EmailId", SqlDbType.VarChar).Value = TextBox4.Text; cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
 con.Close();
}
}
Reply | Email | Modify 
stproces by vasu On March 5, 2009
thanks for giving this
Reply | Email | Modify 
good wishes by pushpendra On May 22, 2009
thank you sir.
   I'm glad because understand stored procedure in very easiet lang. and easily.
          thanks a lot.
Reply | Email | Modify 
Store Procedure by Jagdeep On February 3, 2010
Greate its very usefull for freshers.

Written in very simple language easy to understand all programers.

Greate work.

Well done dude.

== Jagdeep Mankotia
Reply | Email | Modify 
sql parameters by Tom On March 26, 2010
how come sql parameters variables sp1...sp4 never used? can someone give an example of how to use them if needed? much thanks.
Reply | Email | Modify 
great by guriag On July 2, 2010
very nice and simple work
Reply | Email | Modify 
About StoredProcedure Calling by manas On October 29, 2010
Very Nice Description
Reply | Email | Modify 
by using another Database like SQLite by Mani On November 11, 2010
Dear Gaurav,

 plz say how to write the coding .. i mean Commands, Connections .. Instead of SQL.. Whether it is same or Different. i'm using SQLite Database
Reply | Email | Modify 
when i click on submitrecord it shows an error like Procedure 'Submits' expects parameter '@ID', which was not supplied. by Srinu On December 13, 2010
thanks for giving this oppurtunity
Reply | Email | Modify 
Re: when i click on submitrecord it shows an error like Procedure 'Submits' expects parameter '@ID', which was not supplied. by Mani On December 14, 2010
Hi.. The StoreProcedure expecting Parameters.. So you have to pass parameters.. then only it will be Insert in DB.
Reply | Email | Modify 
Re: Re: when i click on submitrecord it shows an error like Procedure 'Submits' expects parameter '@ID', which was not supplied. by kruthika On February 16, 2011
even im getting the same error. kindly help
Reply | Email | Modify 
the code is not working well with me by gigi On December 23, 2010
why you wrote these lines ? SqlCommand cmd = new SqlCommand(); SqlParameter sp1 = new SqlParameter(); SqlParameter sp2 = new SqlParameter(); SqlParameter sp3 = new SqlParameter(); SqlParameter sp4 = new SqlParameter();
Reply | Email | Modify 
Stored Procedeure by chirag On January 1, 2011
Thanks Gaurav.. Do You tell me How To user More Then One Stored Procedure We Can Use in Asp.Net...
Reply | Email | Modify 
how to use stroed procedure using datareader by Rinku On July 16, 2011
how to use stroed procedure using sqldatareader to have one input value and retrieve column in gridview like dept_no as int input and value like name,sal,job etc
Reply | Email | Modify 
code for asp.net by abhishek On January 25, 2012
i hv read ur article on stored procedures,its great. but i need .net code for "when i registered in c#-sharpcorner,within a seconds i got a mail by -memberservices@c-sharpcorner.com. with username & password " so i want to know / code example for how can we send mail to registered users ? please i need an example for the above question and more examples on wcf
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.