Click here to Skip to main content
15,881,600 members
Articles / Web Development / ASP.NET
Article

Insert and retrieve data through stored procedure

Rate me:
Please Sign up or sign in to vote.
1.33/5 (28 votes)
15 Feb 2007CPOL4 min read 297K   5.8K   30   27
All about stored procedure
Sample image

Introduction

There are several advantages of using stored procedures instead of standard SQL. First, stored procedures allow a lot more flexibility offering capabilities such as conditional logic. Second, because stored procedures are stored within the DBMS, bandwidth and execution time are reduced. This is because a single stored procedure can execute a complex set of SQL statements. Third, SQL Server pre-compiles stored procedures such that they execute optimally. Fourth, client developers are abstracted from complex designs. They would simply need to know the stored procedure's name and the type of data it returns.

Creating Stored Procedure?

Enterprise Manager provides an easy way to create stored procedures. First, select the database to create the stored procedure on. Expand the database node, right-click on "Stored Procedures" and select "New Stored Procedure...". You should see the following:

CREATE PROCEDURE [OWNER].[PROCEDURE NAME] AS

Substitute OWNER with "dbo" (database owner) and PROCEDURE NAME with the name of the procedure. For example:

CREATE PROCEDURE [dbo].[GetProducts] AS

So far, we are telling SQL Server to create a new stored procedure with the name GetProducts. We specify the body of the procedure after the AS clause:

CREATE PROCEDURE [dbo].[GetProducts] AS SELECT ProductID, ProductName FROM Products

Click on the Check Syntax button in order to confirm that the stored procedure is syntactically correct. Please note that the GetProducts example above will work on the Northwind sample database that comes with SQL Server. Modify it as necessary to suite the database you are using.

Now that we have created a stored procedure, we will examine how to call it from within a C# application

Calling Stored Procedure

A very nice aspect of ADO.NET is that it allows the developer to call a stored procedure in almost the exact same way as a standard SQL statement.

1. Create a new C# Windows Application project.

2. From the Toolbox, drag and drop a DataGrid onto the Form. Resize it as necessary.

3. Double-click on the Form to generate the Form_Load event handler. Before entering any code, add "using System.Data.SqlClient" at the top of the file.

Enter the following code:

private void Form1_Load(object sender, System.EventArgs e) {

SqlConnection conn = new SqlConnection("Data<br />Source=localhost;Database=db_first;Integrated Security=SSPI");<br />SqlCommand command = new SqlCommand("GetProducts", conn);<br />SqlDataAdapter adapter = new SqlDataAdapter(command);<br />DataSet ds = new DataSet();<br />adapter.Fill(ds, "Products");<br />this.dg_Data.DataSource = ds;
this.dg_Data.DataMember = "Products";

Inserting Data to Stored Procedure

Using other SQL statements such as INSERT, UPDATE or DELETE follow the same procedure. First, create a stored procedure that may or may not accept parameters, and then call the stored procedure from within the code supply the necessary values if parameters are needed. The following example illustrates how to insert a new user in a users table that has a username and password field.

Sql Server Code

CREATE PROCEDURE [dbo].[InsertUser] (<br />@Username varchar(50), @Password varchar(50)<br />)<br />AS INSERT INTO Users VALUES(@Username, @Password)

C# code

string username = Username.Text // get username from user string //<br />password = Password.Text // get password from user 
<p><br />SqlConnection conn = new SqlConnection"<br />DataSource=localhost;Database=db_First;Integrated Security=SSPI");<br />SqlCommand command = new SqlCommand("InsertUser", conn);<br />command.CommandType = CommandType.StoredProcedure;<br />command.Parameters.Add("@Username", SqlDbType.VarChar).Value = username;<br />command.Parameters.Add("@Password", SqlDbType.VarChar).Value = password;<br />conn.Open(); int rows = command.ExecuteNonQuery();<br />conn.Close();</p>

<p>First, we retrieve the username and password information from the user. This information may be entered onto a form, through a message dialog or through some other method. The point is, the user specifies the username and password and the applicaton inserts the data into the database. Also notice that we called the ExecuteNonQuery() method of the Connection object. We call this method to indicate that the stored procedure does not return results for a query but rather an integer indicating how many rows were affected by the executed statement. ExecuteNonQuery() is used for DML statements such as INSERT, UPDATE and DELETE. Note that we can test the value of rows to check if the stored procedure inserted the data successfully. </p>
<code>if (rows == 1) {<br />MessageBox.Show("Create new user SUCCESS!");<br />}<br />else {<br />MessageBox.Show("Create new user FAILED!"); } 

We check the value of rows to see if it is equal to one. Since our stored procedure only did one insert operation and if it is successful, the ExecuteNonQuery() method should return 1 to indicate the one row that was inserted. For other SQL statements, especially UPDATE and DELETE statements that affect more than one row, the stored procedure will return the number of rows affected by the statement.

Conclusion

Stored procedures offer developers a lot of flexibility with many features not available using standard SQL. ADO.NET allows us to use stored procedures in our applications seamlessly. The combination of these two allows us to create very powerful appliations rapidly.

enjoyyyyyyyyyyyyyyyyyyyyyyyyyy

Sample imageSee my Online Profile

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Pakistan Pakistan
Always make your absence felt in such a way that someone misses you but dont let your absense be so long that someone starts learning to live without you.

Comments and Discussions

 
Questionhow to insert data in service based database using stored procedure in c# app Pin
Member 1256268723-Jun-16 3:07
Member 1256268723-Jun-16 3:07 
QuestionRegarding DB Pin
Member 1198024313-Sep-15 19:59
Member 1198024313-Sep-15 19:59 
Questionnice article Pin
bharatwaj vanamamalai28-May-15 4:37
bharatwaj vanamamalai28-May-15 4:37 
QuestionInsertion probelm Pin
master tech15-Aug-14 23:16
master tech15-Aug-14 23:16 
QuestionConfused...!! Pin
sushil shrestha22-May-13 19:01
sushil shrestha22-May-13 19:01 
AnswerRe: Confused...!! Pin
Tariqaziz26-Jun-13 20:33
Tariqaziz26-Jun-13 20:33 
GeneralMy vote of 5 Pin
le dang tuan3-Aug-12 17:13
le dang tuan3-Aug-12 17:13 
GeneralMy vote of 4 Pin
abhihits1-Oct-11 22:54
abhihits1-Oct-11 22:54 
GeneralInsert Data to more than one table with store procedure. Pin
ratulalam15-Mar-11 20:01
ratulalam15-Mar-11 20:01 
QuestionHOW TO: SQL & C# Pin
Shahriar Nour Khondokar2-Jun-10 23:11
Shahriar Nour Khondokar2-Jun-10 23:11 
General[My vote of 1] request Pin
Md. Marufuzzaman2-Nov-09 5:53
professionalMd. Marufuzzaman2-Nov-09 5:53 
GeneralRetrieving values from SQL databases Pin
NithinL20-Jun-08 2:11
NithinL20-Jun-08 2:11 
Generalstored procedures Pin
Mujz.........28-May-07 18:14
Mujz.........28-May-07 18:14 
GeneralIts not working Pin
Mujz.........24-May-07 19:49
Mujz.........24-May-07 19:49 
GeneralRe: Its not working Pin
Christian Graus24-May-07 19:52
protectorChristian Graus24-May-07 19:52 
GeneralRe: Its not working Pin
Mujz.........24-May-07 20:05
Mujz.........24-May-07 20:05 
QuestionHow to read Excel Files in C# Pin
Mujz.........24-May-07 19:17
Mujz.........24-May-07 19:17 
I really need to read an excel file for my assignment . i have to compare the data inj excel with data in the database ..urgent help needed.....D'Oh! | :doh:

Mujtaba Tariq
AnswerRe: How to read Excel Files in C# Pin
Tariqaziz24-May-07 19:38
Tariqaziz24-May-07 19:38 
QuestionDelete Pin
hemalvadgama9-Apr-07 1:05
hemalvadgama9-Apr-07 1:05 
GeneralSP for update and delete Pin
danielwinata30-Mar-07 4:47
professionaldanielwinata30-Mar-07 4:47 
GeneralRe: SP for update and delete Pin
Tariqaziz1-Apr-07 20:43
Tariqaziz1-Apr-07 20:43 
GeneralRe: SP for update and delete Pin
Tariqaziz29-May-07 19:11
Tariqaziz29-May-07 19:11 
GeneralRe: SP for update and delete Pin
danielwinata30-May-07 15:37
professionaldanielwinata30-May-07 15:37 
GeneralRe: SP for update and delete Pin
AmbiguousName14-Jun-11 1:30
AmbiguousName14-Jun-11 1:30 
Generalgood work Pin
Tariqaziz15-Feb-07 21:26
Tariqaziz15-Feb-07 21:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.