Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use SQL Server Stored procedure output in asp.net c# [closed]

I'm new to working with stored procedures.

We have an existing system which uses stored procedures that check usernames and url paths. The Stored procedure will check whether user details exist. If it exists it returns 1 if not it returns 0.

I am trying to write asp.net code to call this stored procedure by providing it with the user details and path and then use the returned 0 or 1 value in asp.net.

like image 583
mshiyam Avatar asked Jan 16 '23 05:01

mshiyam


2 Answers

Looks like you need stored procedure with output parameter

int errorId = 0;

using(SqlConnection sqlConnection = new SqlConnection(connectionString))
{
    using(SqlCommand cmd = new SqlCommand("YourStoredProcedureName", sqlConnection))
    {
    cmd.CommandType=CommandType.StoredProcedure;
    SqlParameter parm=new SqlParameter("@username", SqlDbType.VarChar); 
    parm.Value="mshiyam";
    parm.Direction =ParameterDirection.Input ; 
    cmd.Parameters.Add(parm); 

    SqlParameter parm2=new SqlParameter("@path",SqlDbType.VarChar); 
    parm2.value = "Some Path";
    parm2.Direction=ParameterDirection.Output;
    cmd.Parameters.Add(parm2); 


    SqlParameter parm3 = new SqlParameter("@errorId",SqlDbType.Int);
    parm3.Direction=ParameterDirection.Output; 
    cmd.Parameters.Add(parm3); 

    sqlConnection.Open(); 
    sqlConnection.ExecuteNonQuery();

    errorId = cmd.Parameters["@errorId"].Value; //This will 1 or 0
   }

}
like image 156
HatSoft Avatar answered Feb 01 '23 07:02

HatSoft


Use the following code,

SqlCommand cmd = new SqlCommand("MyStoredProcedure", cn);
cmd.CommandType=CommandType.StoredProcedure;
SqlParameter parm=new SqlParameter("@username",SqlDbType.VarChar);
parm.Value=strUser;
parm.Direction =ParameterDirection.Input ; 
cmd.Parameters.Add(parm); 
parm=new SqlParameter("@url",SqlDbType.VarChar);
parm.Value=strUrl;
parm.Direction =ParameterDirection.Input ; 
cmd.Parameters.Add(parm); 
parm=new SqlParameter("@errorID",SqlDbType.Int); 
parm.Direction=ParameterDirection.Output; // This is important!
cmd.Parameters.Add(parm); 
cn.Open(); 
cmd.ExecuteNonQuery();
cn.Close(); 

// Print the output value
Console.WriteLine(cmd.Parameters["@errorID"].Value); 
Console.ReadLine();
like image 33
Rajesh Subramanian Avatar answered Feb 01 '23 09:02

Rajesh Subramanian