合并语句不适用于OUTPUT子句

时间:2013-09-02 08:07:44

标签: c# sql stored-procedures

我正在从CSV文件中读取数据并将数据放入数据表中。这个dt我发送到存储过程插入/更新。以下是我的存储过程:

* ======================================

ALTER  PROC [dbo].[ups_InsertTVPOrderHeaders]
(
   @tvp [dbo].[TYPOrderHeaders] READONLY
)
AS
    SET NOCOUNT ON;
    DECLARE @InsertOutput TABLE
    (
      MergeAction VARCHAR(20),
      OrderHeaderID int

    );
  BEGIN TRY

  MERGE INTO dbo.OrderHeaders AS T
    USING @tvp AS S
    ON T.OrderHeaderID = S.OrderHeaderID
    WHEN MATCHED THEN 
                  UPDATE SET T.CustomerID = S.CustomerID,
                                 T.FirstName = S.FirstName,
                                 T.LastName = S.LastName

    WHEN NOT MATCHED THEN 
                     INSERT (OrderHeaderID,CustomerID,FirstName,LastName) 
                     VALUES (S.OrderHeaderID,S.CustomerID,S.FirstName,S.LastName)
        OUTPUT $action, inserted.OrderHeaderID INTO @InsertOutput;
        --OUTPUT $action, inserted.OrderHeaderID, Deleted.OrderHeaderID;
        --OUTPUT $action, DELETED.*, INSERTED.*;

      COMMIT TRANSACTION

SELECT * FROM @InsertOutput;        

  END TRY

  BEGIN CATCH

  END CATCH 

* ============================================== =====================

C#代码调用SP部分

  using (SqlConnection con = new SqlConnection(_conStr))
            {
                con.Open();
                using(SqlCommand cmd = new SqlCommand(procedureName, con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlParameter param = cmd.Parameters.AddWithValue("@tvp", SqlDbType.Structured);
                    param.Value = dt;
                    int result = cmd.ExecuteNonQuery();
                    return result;
                }
            }

=============================================== =================================== 我的结果为0。如果我从sp中取出输出条款。它的工作正常。请任何人告诉我输出到声明有什么问题。我想要orderheaderID的插入/更新列表。因此,我尝试使用输出子句。

1 个答案:

答案 0 :(得分:2)

您使用的cmd.ExecuteNonQuery();不会返回结果,只会返回受影响的行数。 According to MSDN这就是ExecuteNonQuery的作用:

  

对连接执行Transact-SQL语句并返回受影响的行数。

您可能想要使用ExecuteReader

using (SqlConnection con = new SqlConnection(_conStr))
{
    con.Open();
    using(SqlCommand cmd = new SqlCommand(procedureName, con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter param = cmd.Parameters.AddWithValue("@tvp", SqlDbType.Structured);
        param.Value = dt;
        using (var reader = cmd.ExecuteReader())
        {
            int result = 0;

            while (reader.Read())
            {
                // Do something with the reader, then increment result by 1 to get total rows affected
                result++;
            }
        }
        return result;
    }
}