插入命令的第二个输出值未在存储过程中返回

时间:2019-08-14 11:19:18

标签: c# sql-server stored-procedures output

当我在存储过程中使用单个插入命令返回插入行的主键时,C#代码可以正常工作。

但是,当试图在2个表中插入一行并获取主键时,C#代码将引发以下错误“ Table2PK”。

MSSQL存储过程脚本:

CREATE PROCEDURE [dbo].[usp_WriteBackStatus] 
    @QtyProduced decimal,
    @QuantityToIssue decimal,
    @Table1PK nvarchar OUTPUT,
    @Table2PK nvarchar OUTPUT
AS
BEGIN  
      INSERT INTO Table1 (QuantityProduced)
      OUTPUT inserted.Table1PK
      VALUES (@QtyProduced)

      INSERT INTO Table2 (QuantityToIssue) 
      OUTPUT inserted.Table2PK
      VALUES (@QuantityToIssue)

END
GO

C#代码:

using (var sqlConnection = new SqlConnection (mConnectionStringSrc)) {
     sqlConnection.Open ();
     using (var sqlCommand = sqlConnection.CreateCommand ()) {
        sqlCommand.Parameters.Clear ();
        sqlCommand.CommandType = CommandType.StoredProcedure;
        sqlCommand.CommandText = "usp_WriteBackStatus";
        sqlCommand.Parameters.Add (new SqlParameter (QtyProduced, 10));
        sqlCommand.Parameters.Add (new SqlParameter (QuantityToIssue, 5));            
        SqlParameter outParam = new SqlParameter ("@Table1PK", SqlDbType.NVarChar, 100);
        outParam.Direction = ParameterDirection.Output;
        sqlCommand.Parameters.Add (outParam);
        outParam = new SqlParameter ("@Table2PK", SqlDbType.NVarChar, 100);
        outParam.Direction = ParameterDirection.Output;
        sqlCommand.Parameters.Add (outParam);
        using (var sqlDataReader = sqlCommand.ExecuteReader ()) {
            while (sqlDataReader.Read ()) {
              var reportedID1 = sqlDataReader["Table1PK"].ToString ();
              var reportedID2 = sqlDataReader["Table2PK"].ToString (); // ERROR "Table2PK" IS THROWN HERE!!!
              Console.WriteLine ($"{reportedID1} {reportedID2}");
            }
        }
    }
}

正如其他SO答案中所建议的那样,我尝试使用表变量来存储输出并设置输出变量,但是出现了以下错误C#代码。

  

将表达式转换为数据类型nvarchar的算术溢出错误。 (在.ExecuteReader()行)

使用表变量时使用的脚本:

DECLARE @OutputData1 table (Table1ID nvarchar);
DECLARE @OutputData2 table (Table2ID nvarchar);
....
OUTPUT inserted.Table1PK INTO @OutputData1 (Table1ID)
OUTPUT inserted.Table2PK INTO @OutputData2 (Table2ID)
....
SELECT @Table1PK = Table1ID, @Table2PK = Table2ID FROM @OutputData1, @OutputData2;
... END ...

1 个答案:

答案 0 :(得分:1)

SQL Server中的output子句返回一个表。
这意味着您的存储过程实际上正在返回两个表,每个表都有一条记录。
IDataReader接口(因此实现了该接口的SqlDataReader)具有一种称为NextResult()的方法,该方法用于将DataReader从当前结果集前进到下一个结果-因此您应该这样做在您的C#代码中是这样的:

string reportedID1 = null, reportedID2 = null;

if(sqlDataReader.Read ()) {
    reportedID1 = sqlDataReader["Table1PK"].ToString ();
    if(sqlDataReader.NextResult())
    {
        if(sqlDataReader.Read ()) {
            reportedID2 = sqlDataReader["Table2PK"].ToString ();
        }
    }
}

// you probably want to check that they are not both null...
Console.WriteLine ($"{reportedID1} {reportedID2}");