Write to output parameter with c#

276 views Asked by At

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?

1

There are 1 answers

0
Anton Ryzhov On BEST ANSWER

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;