Powered By Blogger

Search

Thursday, March 13, 2008

Access a SQL stored procedure

How do I access a SQL stored procedure?

You can access SQL stored procedures the same way as executing other SQL commands. Set the query string as the name of the stored procedure and then set the CommandType to be CommandType.StoredProcedure. Below is an example of one input and one output parameter.

if(myConn.State == ConnectionState.Closed)myConn.Open();
SqlCommand myCmd = new SqlCommand("sp_my_stored_procedure",myConn);
myCmd.CommandType = CommandType.StoredProcedure;
SqlParameter parm;

parm = myCmd.Parameters.Add(new SqlParameter("@custid", SqlDbType.VarChar,50));
parm.Direction = ParameterDirection.Input;
myCmd.Parameters["@custid"].Value = OrderID;
parm = myCmd.Parameters.Add(new SqlParameter("@custName", SqlDbType.VarChar,50));
parm.Direction = ParameterDirection.Output;
SqlDataAdapter da = new SqlDataAdapter();
da.TableMappings.Add("your mapping","your mapping");
da.SelectCommand = myCmd;
DataSet ds = new DataSet();
da.Fill(ds);
DataTable resultTable = ds.Tables[0];

No comments: