Getting a Return Value in C# asp.net from a stored procedure (syntax issue)

后端 未结 4 2021
悲哀的现实
悲哀的现实 2020-12-09 13:51

I am having issues trying to get the syntax correct for my C# 2008 asp.net code. I need to get a return value (Select @@Identity) from my stored procedure

My C# code

4条回答
  •  攒了一身酷
    2020-12-09 13:55

    To capture a RETURN VALUE (returned by SQL using the RETURN({number}) syntax) use:

    cmdHeader.Parameters.Add("@ReturnValue", SqlDbType.Int, 4).Direction = ParameterDirection.ReturnValue;
    

    Also, you should probably be using SCOPE_IDENTITY() instead of @@IDENTITY

    Edit:
    So your sproc would do something like:

    DECLARE @NewId INTEGER
    INSERT SomeTable(FieldA) VALUES ('Something')
    SELECT @NewId = SCOPE_IDENTITY()
    RETURN (@NewId)
    

    And your C# code to retrieve that value would be:

    int newId = cmdHeader.Parameters[@ReturnValue].value;
    

    Edit 2:
    Ok, the original question confused the issue as the "return value" is a different thing to what you're actually doing which is returning a single column resultset.

    So, instead DON'T add a ReturnValue parameter at all. Just use ExecuteScalar() using your original SqlCommand setup as below:

    int newId = Convert.ToInt32(cmdHeader.ExecuteScalar());
    

提交回复
热议问题