2014-05-12 142 views
0

我在這裏有一個問題。我的一些表沒有任何主鍵,但我的觸發器是基於主鍵的工作,是任何解決方案? 例如:沒有主鍵觸發觸發器

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 

回答

0

我的一些表沒有任何主鍵,但我的觸發是工作 基於主鍵,是任何解決方案?

不......你自己說的,你的觸發器是基於主鍵的。

任何原因你沒有在主表上的主鍵?