Use a trigger in SQL Server 2008 R2 to change the value of one column based on the value of another column during update

夙愿已清 提交于 2020-02-08 02:45:17

问题


I need to change the value of a column when a record is updated, based on the value of another column in the same table. The legacy application updating the table cannot be re-coded to handle this.

The basic logic would be:

  • If DateShipped is not null, set OrderLocation = 4

Hoping I can do this at the database level with an update trigger in SQL Server 2008 R2.

thank you.


回答1:


CREATE TRIGGER tr_OrderLocation_Update
ON TableName 
FOR UPDATE,INSERT
BEGIN
  SET NOCOUNT ON;

  UPDATE t
   SET t.OrderLocation = 4
  FROM TableName t INNER JOIN inserted i 
  ON t.PK_Column = i.PK_Column  --<-- what ever the primary key column
  WHERE i.DateShipped IS NOT NULL
END


来源:https://stackoverflow.com/questions/30064311/use-a-trigger-in-sql-server-2008-r2-to-change-the-value-of-one-column-based-on-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!