Monday, July 13, 2009

Use of stored procedure in a table data show

Most of us heard about the stored procedure. I also heard about it but I could not know how to use it. However stored procedure is very helpful for the big queries which is tough to build every time we use. So centrally a function/procedure is stored and called when we need that certain actions it perform....so this is called stored procedure. Here are some tips about stored procedure.

1.create a stored procedure:
How to build a stored procedure: Suppose u want to show info of the students of CSE discipline.
So the code is:

CREATE procedure dbo.showAllInfo
(
/*parameter list*/
@discipline varchar(50)

)
as
select * from Student where discipline=@discipline

EXEC dbo.showAllInfo

Now save the document using any name and execute this sql in VS or any other tools that has access to DB. When it is executed successfully then you will see a new entry called showAllInfo in the stored procedure folder of your DB.

2. Use of stored procedure
Here is how to use stored procedure. Lets take a glance on it. Let we are using SqlConnection object.

try
{
SqlConnection conn=new SqlConnection(ConfigurationManager.ConnectionStrings["MASUDDBConnectionString"].ConnectionString);
conn.open();
SqlCommand comm=new SqlCommand();
comm.Connection=conn;
comm.CommandText="showAllInfo";
comm.CommandType=CommandType.StoredProcedure;
comm.Parameters.AddWithValue("discipline","ParamValue"); /*paramvalue=CSE*/

SqlDataAdapter sda=new SqlDataAdapter(comm);
DataTable dt=new DataTable();
sda.Fill(dt);

/*databinding*/
SomeGridView.dataSource=dt;
SomeGridView.dataBind();

/*results rendered successfully*/

/*closing conn*/
sda.Dispose();
conn.Close();

}
catch(Exception exc)
{
}


No comments:

Post a Comment