从更新列访问值

时间:2014-11-01 01:15:50

标签: sql sql-server

如果我的表格看起来像

+-----------+------------+
| OrderNo   | ShippedDate|   
+-----------+------------+
| 0         | 2013-01-03 |
| 1         | 2013-03-05 |    
| 2         | 2013-01-19 |
| 3         | NULL       | 
| 4         | NULL       | 
+-----------+------------+

它已更新为

+-----------+------------+
| OrderNo   | ShippedDate|   
+-----------+------------+
| 0         | 2013-01-03 |
| 1         | 2013-03-05 |    
| 2         | 2013-01-19 |
| 3         | NULL       | 
| 4         | 2013-05-27 | 
+-----------+------------+

如何访问ShippedDate刚刚更新的OrderNo(在本例中为4)?

我正在尝试创建一个触发器,它将在ShippedDate列上的UPDATE之后触发,我需要让OrderNo与其他具有OrderNo作为外键的表进行一些比较。

2 个答案:

答案 0 :(得分:0)

有一些特殊的表已插入已删除,用于在更新后保存新值和旧值

http://msdn.microsoft.com/en-us/library/ms191300.aspx

答案 1 :(得分:0)

-- You can create an After Update trigger like this:    
CREATE TRIGGER trgAfterUpdate ON [dbo].[tableName] 
FOR UPDATE
AS
    declare @orderNo int;
    declare @shippedDate datetime;

    -- You can store what in the record in variables:
    select @orderNo=i.OrderNo from inserted i;  
    select @shippedDate=i.ShippedDate from inserted i;  

    -- You can check if the values were actually changed or not:
    if update(OrderNo)
            PRINT 'OrderNo updated.'
    if update(ShippedDate)
            PRINT 'ShippedDate was updated.'

GO