How can I return a value as an OUTPUT parameter?

时间:2017-04-06 16:50:34

标签: c# sql

I'm trying to get the OUTPUT parameter to work, but for whatever reason, it's refusing to. I keep getting null as a result. If I do everything on the SQL side, it works fine. I tested it like this,

DECLARE @test INT
EXEC MyProc @number = 1, @id = @test
PRINT @test

which gave me the output exactly as I expected. I've looked over this code for an hour and it looks right. The likely cause is an ID10T error, but my brain just isn't seeing it.

public static int MyFunc(int id)
{
    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["cnString"].ConnectionString))
    {
        connection.Open();

        using (var cmd = new SqlCommand("dbo.MyProc", connection)
        {
            CommandTimeout = 120,
            CommandType = CommandType.StoredProcedure
        })
        {
            cmd.Parameters.AddWithValue("@number", SqlDbType.Int);
            var param = new SqlParameter("@id", SqlDbType.Int)
            {
                Direction = ParameterDirection.Output
            };
            cmd.Parameters.Add(param);
            cmd.ExecuteNonQuery();

            Debug.WriteLine(param.Value);

            return Convert.ToInt32(param.Value);
        }
    }
}

ALTER PROCEDURE dbo.MyProc
(
  @number INT ,
  @id INT OUTPUT
)
AS
    BEGIN
        SET NOCOUNT ON;
        SET @id = (
                             SELECT Id
                             FROM   SomeTable 
                             WHERE SomeValue = @number
                           );
        RETURN;
    END;

2 个答案:

答案 0 :(得分:2)

You have a simple typo ...

You are passing the value of the SqlDbType.Int that you are expecting instead of the parameter to MyFunc.

cmd.Parameters.AddWithValue("@number", SqlDbType.Int);

should be

cmd.Parameters.AddWithValue("@number", id);

答案 1 :(得分:-1)

你可以试试这个:

cmd.Parameters.AddWithValue("@number", SqlDbType.Int).Value = id;
cmd.Parameters.Add(param).Value = id