Tech Junkie Blog - Real World Tutorials, Happy Coding!: ASP.NET: Calling Stored Procedure With A Parameter With SqlParameter Part 6

Monday, February 16, 2015

ASP.NET: Calling Stored Procedure With A Parameter With SqlParameter Part 6

Today we will be calling a stored procedure in SQL Server that we've created earlier in this blog call selProductsBySupplierID.  The stored procedure takes one input parameter call @SupplierID which takes an int.

Sql Parameter

Here is how you would do it in C#

1.  First you need the namespaces

using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data;

2. Then get the Northwind connection string value from the Web.config file
string connectString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].

3. Now call the stored procedure and output the result from the SqlDataReader
  using (SqlConnection conn = new SqlConnection(connectString))
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "selProductsBySupplierID";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;
            SqlParameter parameter = new SqlParameter();
            parameter.ParameterName = "@SupplierID";
            parameter.SqlDbType = SqlDbType.Int;
            parameter.Value = 1;

            SqlDataReader dataReader = cmd.ExecuteReader();

                 while (dataReader.Read())
                     Response.Write("Products: " + dataReader[0] + " $" + 
                     dataReader[1] + "<br>");
In the above code you add the parameter by using SqlParameter. You specify the name, type, and value. Then add it to command object's parameters list. When you execute the reader the parameter @SupplierID is passed into the stored procedure.

Blogs In the T-SQL Series:


  1. The quality of the infrastructure in Estonia is estimated at 3.34. This indicates a satisfactory quality - roads, railways, ports and other facilities can handle significant volumes of traffic at any time, and are also suitable for various types of vehicles and ships.


Search This Blog