WorldofASP.NET : ASP.NET Tutorial, Hosting, and Source Code

WorldofASP.NET >> ASPNET >> Database

Using Stored Procedures with MSSQL and ASP.NET 2.0

This article explain how to migrate your existing in line SQL to Stored Procedures with MSSQL and ASP.NET 2.0

Published Date : 05 Nov 2007

Author : Sanjay Shravan
Language : VB.NET,C#
Platform : .NET
 
Technology : None,ASP.NET
Views : 4023
Rating : (0 votes so far)
Email to a Friend | Print this Article | Add to Favourites | Report Error

Introduction

If you haven't used MSSQL stored procedures before with SQL Server and in your ASP.NET 2.0 pages then you need to read this article. In this article I will list down basic questions like the following :what is a stored procedure? How can I create a stored procedure? How can I use it from within my ASP.NET 2.0 web pages? And how can I return an output parameter value to my ASP.NET web page?

Benefits of Using Stored Procedures Compare to SQL Code.

A stored procedure is a script of SQL code that is stored in your database under a given name. The SQL code for the stored procedure may contain programming logic (using T-SQL IF and CASE statements for example) and SELECT, INSERT, UPDATE or DELETE statements as well.

There are many benefits  using stored procedures instead of writing pure SQL code.
1. Reduce Network Usage between WebServer and Database Server
2. Code Reuse.
3. Faster in performance because they are precompiled and executed quickly
4. Enhance Security as you can only give your user execute permission on your stored procedures but 
    not to the underlying table.

Coding Stored Procedures.

So, Let's Start Coding SQL Stored Procedures in SQL 2005. 

We create T-SQL stored procedure by using the CREATE PROCEDURE statement. To create a stored procedure you use the CREATE PROCEDURE keywords, followed by the name of the stored procedure, followed by the AS keyword. Now you can write the stored procedure's body. Also you may use the keyword PROC instead of PROCEDURE so you can write CREATE PROC.

Let's create a stored procedure called GetCustomerData that returns data from the Customers table of the Northwind database. This procedure will be designed not to return all the columns; instead, it returns only basic information about the customers, namely CustomerID, CompanyName and City.

1. Create Stored Procedures
To create this stored procedure you need to open SQL Server Management Studio or Query analyzer and connect to your database server, then execute the following SQL code:

USE Northwind GO
CREATE PROC GetCustomerData
AS
SELECT CustomerID, CompanyName, City FROM Customers

It's as simple as this. The first line of code changes the current database to Northwind in order to create this stored procedure. Then we create the stored procedure by using the keywords CREATE PROC and give the name of the stored procedure followed by AS and then the SQL query. To use this stored procedure you need to execute it using the keyword EXECUTE (or its shortcut EXEC) as follows:

EXEC GetCustomerData

If you try to run the statement above, you can see the result will be return just like how you execute the select statement, but rather than have to write the full select statement, you can just write exec the stored proc name. It saves you typing time and also code reuse. You can use this stored proc anytime without have to type it all over again. It is precompiled and saved into database.

And also imagine, if you try to run this code on your web server,and if you used to type the inline sql in your code, then you are advised to migrate all your inline sql into stored proc. It will save your network usage between the web server and database server. This is because you only send "Exec Stored proc text" from your web server to database server, rather than have to send the whole queries across the network. It will greatly enhance your web site performance.

2. Editing Your Stored Procedures
To Edit your Current Stored Procedures on your Database, you can run ALTER Statement. Below is the sample SQL Code.

USE Northwind GO
ALTER PROC GetCustomerData
AS
SELECT CustomerID, CompanyName, City FROM Customers

Sample Code in ASP.NET

Now Let's start create a web page to execute the GetCustomerData Stored Procedure. Start by creating a new website and add the following code to the Page_Load() event handler method of the Default.aspx.cs file.

protected void Page_Load(object sender, EventArgs e) {
    string connectionString = "Data Source=(local);Initial    Catalog=Northwind;Integrated Security=True";
    SqlConnection connection= null;
    try
    {
        connection  = new SqlConnection(connectionString);
        string commandText = "GetCustomerData";
        SqlCommand command = new SqlCommand(commandText, connection);
        command.CommandType = CommandType.StoredProcedure;
        connection.Open();
	
        SqlDataReader dataReader = command.ExecuteReader();
        while (dataReader.Read())
        {
            Response.Write(" <B>" + dataReader["CustomerID"] + " </B>" + ", " +
            dataReader["CompanyName"] + ", " + dataReader["City"] + " <BR>");
        }
        dataReader.Close();
 
     }
     catch (Exception ex)
     {
        Response.Write(ex.Message);
     }
     finally {
         connection.Close();
     }
}

3. Using Stored Procedures with Input and Output Parameters

In the sample above, you have seen that we call stored procedures without actually passing any parameters. You can also pass input and output parameters in your stored procedures.
Below is the sample code on how to achieve that

CREATE PROCEDURE InsertEmployee
(@LastName VARCHAR(40),
@FirstName VARCHAR(30),
@Title VARCHAR(40),
@City VARCHAR(25),
@Country VARCHAR(15),
@EmployeeID INT OUTPUT)
AS
INSERT INTO Employees(LastName,FirstName,Title,City,Country) VALUES(@LastName,@FirstName,@Title,@City,@Country)
SET @EmployeeID = SCOPE_IDENTITY()

If you see the stored procedures above, you can see that we are trying to create new entry for Employees table. And it will return the EmployeeID as an output. Because EmployeeID is declared as identity, the only way we can get the values is by using SCOPE_IDENTITY function and we set that into our output variables. SCOPE_IDENTITY() function is used to get the last IDENTITY value inserted at a column defined as IDENTITY in the current scope.

Now, if we want to run the Stored Procedures above, we need to do like this
DECLARE @NewEmployeeID int
EXEC InsertEmployee @LastName = 'Douglas',
               @FirstName = 'James',
               @Title = 'IT Support',
               @City = 'Texas',
               @Country = 'USA',
               @EmployeeID = @NewEmployeeID OUTPUT
SELECT @NewEmployeeID

Sample Code in ASP.NET
protected void Page_Load(object sender, EventArgs e) {
   string connectionString = "Data Source=(local);InitialCatalog=Northwind;Integrated Security=True";
   SqlConnection connection;
   try
   {
       connection = new SqlConnection(connectionString);
       string commandText = "InsertEmployee";
       SqlCommand command = new SqlCommand(commandText, connection);
       command.CommandType = CommandType.StoredProcedure;
       command.Parameters.AddWithValue("@LastName","Douglas");
       command.Parameters.AddWithValue("@FirstName","James");
       command.Parameters.AddWithValue("@Title", "IT Support");
       command.Parameters.AddWithValue("@City", "Texas");
       command.Parameters.AddWithValue("@Country","USA");
    
       SqlParameter outParameter = new SqlParameter();
       outParameter.ParameterName = "@EmployeeID";
       outParameter.Direction = ParameterDirection.Output;
       outParameter.DbType = DbType.Int32;
       command.Parameters.Add(outParameter);
       connection.Open();

       int rowsAffected = command.ExecuteNonQuery();
       if (rowsAffected == 1)
       {
           Response.Write("1 rows have been affected with this operation <BR><BR>");
       }
       Response.Write("Employee ID = " + command.Parameters["@EmployeeID"].Value);
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
    finally {
        connection.Close();
    }
}
    If you see the code above, you can see that it is quite simple. For output parameters, we need to set the parameter direction to ParameterDirection.Output. And after you execute the command, you can get the value back into your code, by running the command.Parameters["@EmployeeID"].
    After you have seen the code above, you can see that the code is infact cleaner and easy to read compare to using inline sql where you have to keep append the string and form the sql.
    That's all for now. Happy Coding SQL!! 


      Other Related and Popular Articles :

      Basic Introduction to ADO.NET in ASP.NET
      This article provides information on programming with ADO.NET including DataSet,DataAdapter and DataReader
      Improve Your DataGrid Paging performance
      Tips and tricks on how to improve your DataGrid Paging performance
      Using Codesmith and .netTiers to build a Data Access Layer
      Tutorial about how to connect database with asp.net and vb.net using Codesmith and .netTiers tools

      Author Profile : Sanjay Shravan

      Click here to view Author Profile


      How would you rate the quality of this content?
      Poor Excellent

      Comments

      Leave New Comments


      Article Content copyright by Sanjay Shravan
      Everything else Copyright © by WorldofASP.NET 2008
       
      Announcements
      Earn Cash Now







      Legend : - Within 3 Days - Within 6 Days - Within 9 Days

      Home | Add Resources | Sponsored Listings | Advertise with Us | Contact Us | SiteMap | Link To Us | Contact Us
      © 2002-2008 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
      Our Partners : ASP.NET Web Hosting | Windows Web Hosting | FREE ASP.NET CMS | Phone Card | PHP Directory | Bangkok Hotels |Calling Card