如何使用存储过程访问插入和删除的逻辑表

时间:2019-01-07 15:29:37

标签: sql-server tsql

是否可以使用存储过程或函数 WITHOUT 使用触发器或从触发器传递值来访问inserteddeleted表。

例如:

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查询访问inserteddeleted表?

1 个答案:

答案 0 :(得分:2)

您只能在触发器或output语句的DML子句中使用inserteddeleted表。

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所示。