1

In SQL Server, I can pass a value IN to a stored procedure output parameter, alter it, and then read it back:

CREATE PROCEDURE [dbo].[testSP]
    @myOutputParam INT OUTPUT
AS
BEGIN
    SELECT @myOutputParam = @myOutputParam + 1
END
GO

DECLARE @x int = 1

EXEC testSP @myOutputParam = @x OUTPUT

PRINT @x -- prints: 2

However, when I try and do this from C#, it does not work:

using (SqlConnection db = new SqlConnection("..."))
using (SqlCommand cmd = new SqlCommand("testSP", db))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@myOutputParam", SqlDbType.Int).Value = (int)1;
    cmd.Parameters["@myOutputParam"].Direction = ParameterDirection.Output;

    db.Open();

    int rowsAffected = cmd.ExecuteNonQuery();
    int x = (int)cmd.Parameters["@myOutputParam"].Value;
}

The final int x assignment throws an error

Specified cast is not valid

Where am I going wrong?

2
  • 1
    what is the result of cmd.Parameters["@myOutputParam"].Value without casting? Commented Sep 20, 2017 at 6:50
  • @SeM I think its an empty object. Its not null because the cast still fails even if I use int? x = (int?)cmd.Parameters["@myOutputParam"].Value; Commented Sep 20, 2017 at 7:05

1 Answer 1

8

The stored procedure assigns null to the output parameter as the result of calculation because it is specified as output only.

The actual parameter direction is input and output:

cmd.Parameters["@myOutputParam"].Direction = ParameterDirection.InputOutput;
Sign up to request clarification or add additional context in comments.

Comments

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.