是否可以使用存储过程或函数 WITHOUT 使用触发器或从触发器传递值来访问inserted
和deleted
表。
例如:
INSERT INTO dbo.Table (ID)
VALUES (1)
SELECT * FROM inserted -> This raises an error
是否有一种方法可以执行以下操作以捕获插入的值?
我能够对使用MERGE
命令的查询执行以下操作。
MERGE Products AS TARGET
USING UpdatedProducts AS SOURCE ON (TARGET.ProductID = SOURCE.ProductID)
WHEN MATCHED AND TARGET.ProductName <> SOURCE.ProductName
OR TARGET.Rate <> SOURCE.Rate
THEN
UPDATE SET TARGET.ProductName = SOURCE.ProductName,
TARGET.Rate = SOURCE.Rate
WHEN NOT MATCHED BY TARGET
THEN
INSERT (ProductID, ProductName, Rate)
VALUES (SOURCE.ProductID, SOURCE.ProductName, SOURCE.Rate)
WHEN NOT MATCHED BY SOURCE
THEN
DELETE
OUTPUT
$action,
DELETED.ProductID AS TargetProductID,
DELETED.ProductName AS TargetProductName,
DELETED.Rate AS TargetRate,
INSERTED.ProductID AS SourceProductID,
INSERTED.ProductName AS SourceProductName,
INSERTED.Rate AS SourceRate;
是否可以通过简单的SQL查询访问inserted
和deleted
表?
答案 0 :(得分:2)
您只能在触发器或output
语句的DML子句中使用inserted
和deleted
表。
在insert
语句中,output
子句可以引用inserted
表:
DECLARE @Ids AS TABLE (id int);
INSERT INTO dbo.Table (ID)
OUTPUT Inserted.ID INTO @Ids(id)
VALUES (1), (2), (3);
在update
语句中,您可以同时引用inserted
表和已删除表:
DECLARE @Ids AS TABLE (oldId int, newId int);
UPDATE dbo.Table
SET ID = 1
OUTPUT Deleted.ID, Inserted.ID INTO @Ids(oldId, newId);
在delete
语句中,您可以引用deleted
表:
DECLARE @Ids AS TABLE (id int);
DELETE dbo.Table
OUTPUT Inserted.ID INTO @Ids(id)
FROM dbo.Table
WHERE ID IN (1, 2, 3);
Merge
语句是唯一的,因为您可以访问源表及其输出子句中的inserted
/ deleted
表,如on this post所示。