0

我正在从 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 的插入/更新列表。因此,我尝试使用输出子句。

4

1 回答 1

2

您正在使用cmd.ExecuteNonQuery();which 不会返回结果,只会返回受影响的行数。根据 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;
    }
}
于 2013-09-02T08:21:12.797 回答