我有一个 SQL 触发器 FOR INSERT, UPDATE 我创建了它基本上执行以下操作:
从 Inserted 表中获取 LineID(表的 PrimaryID)和 RegionID,并将其存储在 INT 变量中。然后它会检查连接表以查找 RegionID 应该是什么,如果 RegionID 不等于它应该来自 Inserted 表的值,那么它应该更新该记录。
CREATE TRIGGER [dbo].[TestTrigger]
ON [dbo].[PurchaseOrderLine]
FOR INSERT, UPDATE
AS
-- Find RegionID and PurchaseOrderLineID
DECLARE @RegionID AS INT
DECLARE @PurchaseOrderLineID AS INT
SELECT @RegionID = RegionID, @PurchaseOrderLineID = PurchaseOrderLineID FROM Inserted
-- Find PurchaserRegionID (if any) for the Inserted Line
DECLARE @PurchaserRegionID AS INT
SELECT @PurchaserRegionID = PurchaserRegionID
FROM
(...
) UpdateRegionTable
WHERE UpdateRegionTable.PurchaseOrderLineID = @PurchaseOrderLineID
-- Check to see if the PurchaserRegionID has a value
IF @PurchaserRegionID IS NOT NULL
BEGIN
-- If PurchaserRegionID has a value, compare it with the current RegionID of the Inserted PurchaseOrderLine, and if not equal then update it
IF @PurchaserRegionID <> @RegionID
BEGIN
UPDATE PurchaseOrderLine
SET RegionID = @PurchaserRegionID
WHERE PurchaseOrderLineID = @PurchaseOrderLineID
END
END
我遇到的问题是它没有更新记录,我猜,这是因为该记录尚未插入到 PurchaseOrderLine 表中,我正在对此进行更新。但是你能更新从 Inserted 表中插入的行吗?