Retrieving SQL Server output variables in c#

后端 未结 5 1405
醉梦人生
醉梦人生 2020-12-18 04:25

I have a stored procedure:

ALTER PROCEDURE [dbo].[pr_Tbl_Test_Insert]
    @guidid uniqueidentifier output,
    @sname nvarchar(50)
AS
-- INSERT a new row in          


        
5条回答
  •  执念已碎
    2020-12-18 05:01

    First of all - if it's an OUTPUT parameter, you cannot use .AddWithValue in C# - you need to use:

    SqlParameter outParam = cmd.Parameters.Add("@guidid", SqlDbType.Uniqueidentifier);
    outParam.Direction = ParameterDirection.Output;
    

    and also, in your T-SQL code, you need to assign the new value to the output parameter!

    ALTER PROCEDURE [dbo].[pr_Tbl_Test_Insert]
      @guidid uniqueidentifier output,
      @sname nvarchar(50)
    AS
    
    DECLARE @NewID UNIQUEIDENTIFIER
    SET @NewID = newid();
    
    -- INSERT a new row in the table.
    INSERT [dbo].[Tbl_Test]([id], [name]) VALUES(@NewID, @sname);
    
    SET @guidid = @NewID
    

    Update: if you run this in your SQL Server Mgmt Studio - does it show anything??

    DECLARE @insertedID UNIQUEIDENTIFIER
    
    EXEC dbo.pr_Tbl_Test_Insert @guidid = @insertedID OUTPUT,
                                @sname = N'TestUser' -- nvarchar(50)
    
    SELECT @insertedID
    

    and in your C# - you have to read out the value of the output parameter after calling ExecuteNonQuery!

    SqlParameter outparam = cmd.Parameters.Add("@guidid",SqlDbType.UniqueIdentifier);
    outparam.Direction = ParameterDirection.Output;
    
    cmd.Parameters.AddWithValue("@sname", "mehdi");
    
    cmd.ExecuteNonQuery();
    
    Guid newlyInsertedID = new Guid(cmd.Parameters["@guidid"].Value);
    MessageBox.Show(newlyInsertedID.ToString());
    

提交回复
热议问题