我需要創建一個觸發器,它將有關價格變化的信息插入另一個表中。下面我介紹我的解決方案。使用有關表更新的日誌信息創建觸發器
CREATE TABLE Production.Products_AUDIT
(
auditid INT NOT NULL IDENTITY,
productid INT NULL,
old_price MONEY NOT NULL,
new_price MONEY NOT NULL,
CONSTRAINT PK_Products_AUDIT PRIMARY KEY(auditid),
CONSTRAINT FK_Products_AUDIT_AUDIT
FOREIGN KEY(productid) REFERENCES Production.Products(productid)
);
INSERT INTO Production.Products_AUDIT VALUES (1, 18 , 20)
INSERT INTO Production.Products_AUDIT VALUES (2, 19 , 31)
DELETE FROM Production.Products_AUDIT
SELECT unitprice
FROM Production.Products_AUDIT as p1
INNER JOIN Production.Products as p2 on p1.productid = p2.productid
CREATE TRIGGER trig1
ON Production.Products
FOR UPDATE
AS
declare @prodId INT
declare @oldPrice MONEY
declare @newPrice MONEY
SET @prodId = (SELECT i.productid
FROM inserted as i
INNER JOIN Production.Products as pp on i.productid = pp.productid)
SET @oldPrice = (SELECT i.unitprice
FROM deleted as i
INNER JOIN Production.Products as pp on i.productid = pp.productid)
SET @newPrice = (SELECT i.unitprice
FROM inserted as i
INNER JOIN Production.Products as pp on i.productid = pp.productid)
INSERT INTO Production.Products_AUDIT
VALUES(@prodId, @oldPrice, @newPrice)
UPDATE Production.Products
SET unitprice = 45
WHERE productid < 2
SELECT * FROM Production.Products_AUDIT
當我只更新一條記錄時,一切正常。問題是,當我嘗試更新多條記錄,然後我看到下面的錯誤:
消息512,級別16,狀態1,過程TRIG1,41號線
子查詢返回多個值。當子查詢遵循=,!=,<,< =,>,> =或當子查詢用作表達式時,這是不允許的。 聲明已被終止。
有誰知道如何解決這個問題?
@XING不,這不是個好主意,尤其是在觸發器中。基於集合的方法是這裏需要的。 –