0

Is there a way to read some custom return parameters from a stored procedure by name in C#? The iterative way works like this:

SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
    while (rdr.Read())
    {
        if (rdr[0] != null)
        {
            string PARAM1 = rdr[0].ToString();
        }
        if (rdr[1] != null)
        {
            string PARAM2 = rdr[1].ToString();
        }
        if (rdr[2] != null)
        {
            string PARAM3 = rdr[2].ToString();
        }
        if (rdr[3] != null)
        {
            string PARAM4 = rdr[3].ToString();
        }
    }
}
rdr.Close();

the procedure returns something like this:

SELECT 
    'value1' AS 'PARAM1', 
    199 AS 'PARAM2', 
    'value2' AS 'PARAM3', 
    'value3' AS 'PARAM4'
RETURN 0

..but that solution is not satisfying to get a param by name or by type.

5
  • 1
    Do you really mean return parameters, meaning the parameter direction is ReturnValue? Or are you talking about the result set? Commented Jun 18, 2018 at 11:50
  • It is rdr[name] instead of a number. Commented Jun 18, 2018 at 11:54
  • Can you explain what is not working the way you want? I can tell you that if the reader has more than one row you will overwrite the PARAMx variables on each loop iteration and that is probably not what you would want. Commented Jun 18, 2018 at 12:01
  • @UweKöhler you don't need a parameter you can access it by rdr["PARAM1"] directly Commented Jun 18, 2018 at 14:11
  • the access with parameter name: rdr[name] doesn't work because the name is unknown Commented Jul 9, 2018 at 11:46

1 Answer 1

1

Use the parameter name and get the value like this:

Param4 = rdr["@YourOutputParameter"].Value

May be you need to cast it to the type that you expected, for string use:

Param4 = rdr["@YourOutputParameter"].Value.ToString();
Sign up to request clarification or add additional context in comments.

2 Comments

the access with parameter name doesn't work for me because the name is unknown. May be because it's not defined inside SQL as out parameter?
@UweKöhler make sure that the name of the column that you try to get the value or the column alias exist in the columns returned in the select statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.