通过表更新获得修改

时间:2016-03-30 11:02:19

标签: sql-server triggers

是否可以让用户修改db中的行。我可以获得ModifiedOn日期。我的代码如下;

CREATE TRIGGER trgUpdate
ON Table1
FOR UPDATE
AS
BEGIN
IF @@ROWCOUNT = 0   RETURN
IF TRIGGER_NESTLEVEL(object_ID('trgUpdate')) > 1  RETURN;
SET NOCOUNT  ON;



UPDATE Table1
SET    ModifiedOn = CURRENT_TIMESTAMP
FROM   Table1 c
       INNER JOIN INSERTED i
         ON c.accID = i.accID
END

2 个答案:

答案 0 :(得分:1)

如果Table1ModifiedBy列,那么这应该有效

UPDATE Table1
SET    ModifiedOn = CURRENT_TIMESTAMP,
       ModifiedBy = SUSER_SNAME()
FROM   Table1 c
       INNER JOIN INSERTED i
         ON c.accID = i.accID

答案 1 :(得分:1)

要确定在SQL trigger内的表上插入,更新,删除命令后更改了哪些列,您可以使用应用逻辑

create trigger tr_DataTable on DataTable after update, insert, delete
as
begin

select
    ColumnA = case when i.ColumnA = d.ColumnA then 'not changed' else 'changed' end,
    ColumnB = case when i.ColumnB = d.ColumnB then 'not changed' else 'changed' end
from inserted i
full outer join deleted d on i.ColumnA = d.ColumnA

end

在此示例中,我假设ColumnA是DataTable表的PK字段 如果插入字段值与已删除字段值不同,则会显示相关字段上的数据已更新

虽然SQL提供了一种使用Columns_Updated确定更新列的方法,但它是按位的,我觉得很难应用。所以我更喜欢上面的逻辑

alter trigger tr_DataTable on DataTable after update, insert, delete
as
begin

select
    FirstColumn = case when COLUMNS_UPDATED() & 2^0 = 0 then 'not changed' else 'changed' end,
    SecondColumn = case when COLUMNS_UPDATED() & 2^1 = 0 then 'not changed' else 'changed' end

end