Merge语句不能与OUTPUT子句一起使用
本文关键字:一起 子句 OUTPUT 语句 不能 Merge | 更新日期: 2023-09-27 18:29:48
我正在从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.中去掉ouput子句,它就行了。请任何人告诉我在输出到语句中出了什么问题。我想要orderheaderID的插入/更新列表。因此,我尝试使用output子句。
您使用的是cmd.ExecuteNonQuery();
,它不会返回结果,只返回受影响的行数。根据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;
}
}