Wednesday, June 10, 2009

Return value from stored procedure to c#

Suppose you have a stored procedure which returns a bit value 0 or 1. If you want to call that procedure from c# and get that bit value, do like this below:

let say, the stored procedure has:

Name: dbo.sp_dateCheck

Variables:
@laptop varchar(50),
@startdate DateTime,
@enddate DateTime

and return bit variable: @CondFlag

SqlCommand com = new SqlCommand("dbo.sp_dateCheck", conn);
com.CommandType = CommandType.StoredProcedure;

try
{
conn.Open();
com.Parameters.Add(new SqlParameter("@laptop", Laptop.Text));
com.Parameters.Add(new SqlParameter("@startdate", startDate. DateTime));
com.Parameters.Add(new SqlParameter("@enddate", endDate. DateTime));

//read the returned value from stored procedure
com.Parameters.Add("@CondFlag", SqlDbType.Bit);
com.Parameters["@CondFlag"].Direction = ParameterDirection.ReturnValue;
com.ExecuteNonQuery();
int ReturnedVal = (int)com.Parameters["@CondFlag"].Value;

if (ReturnedVal == 0)
{ // do this
}

else
{//do this
}
}

catch
{
}

Happy Programming!!!

No comments:

Post a Comment

Highly Appreciated your comments