避免使用SQL Server触发器进行列更新

时间:2018-07-15 18:42:39

标签: sql-server tsql triggers

我有一个表Product,其中有列iddescriptioncurrentStock。我想避免使用currentStock触发器来更新INSTEAD OF UPDATE

我尝试更新触发器中的所有其他列,但无法在更新语句上引用Inserted伪表。

我该怎么办?是否有更好的方法避免在currentStock列上进行更新?

CREATE TRIGGER T9 ON Product 
INSTEAD OF UPDATE
AS 
    UPDATE Product
    SET Product.id = inserted.id???? ,
        Product.description =  inserted.description??????

1 个答案:

答案 0 :(得分:0)

如果适用,您可以拒绝在特定列上进行更新:

DENY UPDATE ON dbo.Product(currentStock) TO user_name;  --role name

更新语句不能引用该列,否则您将得到错误。

UPDATE Product
SET currentStock = ?
WHERE ...;
-- error

UPDATE Product
SET currentStock = ?
  ,description = ?
WHERE ...;
-- error

UPDATE Product
SET description = ?
WHERE ...;
-- will run successfully

并带有触发器:

CREATE TRIGGER T9 ON Product INSTEAD OF UPDATE
AS 
UPDATE p
SET description = i.description
FROM Product p
JOIN inserted i
  ON p.id = i.id;

DBFiddle Demo