Sunday, March 23, 2014

sql server execute stored procedure with return value

To Execute stored procedure that return value and get result you should do th following
1- declare variable with Type match return value .
2- write Execute command EXEC
3- set variable declared = function call with parmeter.
example

declare @valback int;
exec @valback =VACATION_REPORTS_REQUEST_GET_INBOX_REQUESTS_COUNT 29 , 3;
SELECT  @valback;
------------------------------------------------------------------------------------------------
to get return value using stored procedure
you can use this template to get return value

 public string GetSingelvalue_SQLReturnValue(string Stored, params string[] p)
    {
        try
        {
            cmd = new SqlCommand(Stored, cn);
            cmd.CommandType = CommandType.StoredProcedure;
            for (int i = 0; i < p.Length; i = i + 2)
            {
                cmd.Parameters.Add(new SqlParameter(p[i], p[i + 1]));
            }
            var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);
            returnParameter.Direction = ParameterDirection.ReturnValue;
            if (cn.State == ConnectionState.Closed)
                cn.Open();
            cmd.ExecuteNonQuery();
            if (cn.State == ConnectionState.Open)
                cn.Close();
            var result = returnParameter.Value;
            return result.ToString();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        finally
        {
            if (cn.State == ConnectionState.Open)
                cn.Close();

        }
    }

No comments:

Post a Comment