sql-server - 在不使用输出的情况下通过 MERGE 的操作获取受影响行的行数
问题描述
我试图在合并语句之后通过操作(更新、插入、删除)获取受影响行的计数。由于我需要的唯一信息是计数,因此我宁愿避免将数据输出到单独的时间来处理时间问题。
我可以执行单独的插入、更新和删除语句,并从@@ROWCOUNT 获取我需要的信息。通过合并,我可以将数据输出到另一个表中,然后以结果为中心,但我希望像@@ROWCOUNT 这样的显式操作更灵活一些。
当前解决方案:
--Mock up a target table and a source table and populate with some data
DROP TABLE IF EXISTS TargetTable
CREATE TABLE TargetTable
(
Field1 int,
Field2 int,
Field3 int,
Field4 int
)
DROP TABLE IF EXISTS SourceTable
CREATE TABLE SourceTable
(
Field1 int,
Field2 int,
Field3 int,
Field4 int
)
INSERT INTO SourceTable
(
Field1,
Field2,
Field3,
Field4
)
VALUES ( 1, 2, 3, 7 ),
( 1, 2, 4, 7 ),
( 1, 2, 5, 7 ),
( 1, 2, 6, 7 ),
( 2, 1, 1, 7 ),
( 2, 1, 2, 7 )
--Make a table to hold output
DROP TABLE IF EXISTS #Output
CREATE TABLE #Output
(
[Action] nvarchar(10)
)
--Write a merge with the actions outputed into our temp table
MERGE TargetTable AS Target
USING SourceTable AS Source
ON ( Target.Field1 = Source.Field1
AND Target.Field2 = Source.Field2
AND Target.Field3 = Source.Field3 )
WHEN NOT MATCHED BY Target
THEN INSERT ( Field1,
Field2,
Field3,
Field4 )
VALUES ( Source.Field1,
Source.Field2,
Source.Field3,
Source.Field4 )
WHEN MATCHED
THEN UPDATE SET Target.Field4 = Source.Field4
WHEN NOT MATCHED BY Source
THEN DELETE
OUTPUT $Action INTO #Output;
--Pivot the results to get output by action
SELECT [INSERT],
[UPDATE],
[DELETE]
FROM #Output
PIVOT ( COUNT( [Action] ) FOR [Action] IN ( [INSERT],
[UPDATE],
[DELETE] ) ) AS PivotedOutput
解决方案
推荐阅读
- asp.net - ASP.NET Core 2 TagHelper 代码未执行
- python - 居中数据框图
- google-chrome - Jenkins 中的 TestCafe 无法建立浏览器连接
- javascript - 如何使用不直接导出的组件?
- asp.net - 在调用 HttpRequest.ValidateString() 之前修改 asp 文本框
- angular - prime-ng 下拉菜单上的 prime-ng 工具提示
- angular - 在 Map 之前按嵌套数组中的值排序
- php - 使用 Node 或 PHP 使用 SOAP WS-Security
- for-loop - 重置循环变量
- r - 在 R 中使用具有 HVDM 度量的 distances() 函数计算对之间的距离