对于触发器中的inserted和deleted如何查询出一个表,表中含有所有值不同的列名?
结果集中每一行是一个列的名字

解决方案 »

  1.   

    对于下面的行,改动了列a,c,d
    id   a   b   c   d
    100  1   2   3   4
    成为
    id   a   b   c   d
    100  11  2   33  44
    查询出下表
    col_name  old_val   new_val
    a         1         11
    c         3         33
    d         4         44
      

  2.   

    -- Test Data: ta
    If object_id('ta') is not null 
        Drop table ta
    Go
    Create table ta(id int,a int,b int,c int,d int)
    Go
    Insert into ta
    select 100,1,2,3,4 
    Go
    -- Test Data: tb
    If object_id('ta') is not null 
        Drop table tb
    Go
    Create table tb([col_name] varchar(3),old_val int,new_val int)
    Go
    --Start
    create trigger triggername
    on ta
    for update
    as
    begin
        if update(id)
             insert tb select 'id',d.id ,i.id from inserted i ,deleted d where i.id = d.id
        if update(a)
             insert tb select 'a',d.a ,i.a from inserted i ,deleted d where i.id = d.id
        if update(b)
             insert tb select 'b',d.b ,i.b from inserted i ,deleted d where i.id = d.id
    end
    goupdate ta
    set a = 11,b= 12
    Select * from tb
    --Result:
    /*
    col_name old_val     new_val     
    -------- ----------- ----------- 
    a        1           11
    b        2           12(所影响的行数为 2 行)*/
    --End 
      

  3.   

    看SQL什么时候可以写循环的时候,楼主就更方便了.
      

  4.   

    SQL能写循环,但是我不会写这个功能
      

  5.   

    用动态SQL语句,到SYSOBJECTS和SYSCOLUMN表中取
      

  6.   

    对单条记录的update可行,如同时更新多条记录,如何显示?
      

  7.   


    不好写,因为inserted、deleted 表都是需表,没有存在表结构
      

  8.   

    其实不需要用触发器做,可以直接用sql语句实现
      

  9.   

    今天尝试了下从系统表取列名的方式,真是郁闷死
    用动态SQL语句提示
    它告诉你只能在 CREATE TRIGGER 语句内部使用 IF UPDATE。EXEC执行的动态语句被视作是触发器外部
    用变量写成简单的如下语句又被告知消息 102,级别 15,状态 1,过程 triggername,第 8 行
    '@colname' 附近有语法错误。
    create trigger triggername
    on ta
    for update
    as
    begin
        declare @colname varchar(8)
        set @colname='b'
        if update(@colname)
        begin
        insert tb select @colname,d.id ,i.id from inserted i ,deleted d where i.id = d.id
        end
    end真是一点办法也没有
    目前:只能是有多少列就得写多少if语句了!