在没有主键的情况下触发触发器

时间:2014-05-12 02:30:19

标签: sql triggers primary-key

我在这里有一个问题。我的一些表没有任何主键,但我的触发器是基于主键的工作,是否有任何解决方案? 例如:

create trigger tr_tableA on dbo.tableA
after update
as

declare
@bit int,
@field int ,
@maxfield int,
@char int,
@fieldname varchar(128),
@TableName varchar(128),
@PKCols varchar(500),
@sql varchar(2000),
@Type char(1),
@PKSelect varchar(500),


select @TableName = 'tableA'


if exists(select * from inserted)
        if exists(select * from deleted)
                    select @Type = 'U'
        else                        
        print('do nothing')

select * into #ins from inserted
select * into #del from deleted

select  @PKCols = coalesce(@PKCols + ' and', ' on') + ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME
from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
where   pk.TABLE_NAME = @TableName
and CONSTRAINT_TYPE = 'PRIMARY KEY'
and c.TABLE_NAME = pk.TABLE_NAME
and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME


if @PKCols is null
begin
    raiserror('no PK on table %s', 16, -1, @TableName)
    return
end

select @field = 0, @maxfield = max(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName 
while @field < @maxfield
begin

    select @field = min(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName and ORDINAL_POSITION > @field
    select @bit = (@field - 1 )% 8 + 1
    select @bit = power(2,@bit - 1)
    select @char = ((@field - 1) / 8) + 1
    if substring(COLUMNS_UPDATED(),@char, 1) & @bit > 0 or @Type in ('U')
    begin

    select @fieldname = COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName and ORDINAL_POSITION = @field 
        select @sql =       'insert into tableB (Description, OldValue, NewValue)'
        select @sql = @sql +    ' select ''' + @fieldname + ''''
        select @sql = @sql +    ',d.' + @fieldname + ''
        select @sql = @sql +    ',i.' + @fieldname + ''
        select @sql = @sql +    ' from #ins i full outer join #del d '
        select @sql = @sql +    @PKCols
        select @sql = @sql +    ' where i.' + @fieldname + ' <> d.' + @fieldname 
        select @sql = @sql +    ' or (i.' + @fieldname + ' is null and  d.' + @fieldname + ' is not null)' 
        select @sql = @sql +    ' or (i.' + @fieldname + ' is not null and  d.' + @fieldname + ' is null)' 

        exec (@sql)

    end

end

1 个答案:

答案 0 :(得分:0)

  

我的一些桌子没有任何主键,但我的触发器是有效的   基于主键,是否有任何解决方案?

没有......你自己说过,你的触发器是基于主键的。

您在桌面上没有主键的原因是什么?