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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
mulllhausen
  • 4,225
  • 7
  • 49
  • 71
  • 1
    what is the result of `cmd.Parameters["@myOutputParam"].Value` without casting? – SᴇM Sep 20 '17 at 06: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;` – mulllhausen Sep 20 '17 at 07:05

1 Answers1

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;
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Anton Ryzhov
  • 131
  • 2