日期:2014-05-18  浏览次数:20615 次

急求触发器解答
我刚开始用触发器,请向大家请教一个问题:我写了一个触发器如下:
CREATE   TRIGGER   [forbidToDeleteCompany]   ON   [dbo].[Company]  
FOR   DELETE  
AS
begin

declare   @tableName   varchar(255)
declare   @fieldName   varchar(255)
declare   @tcount   int
DECLARE   tableFieldCursor   CURSOR   FOR  
select   t.[name]   as   tableName,f.[name]   as   fieldName
from   sysobjects   as   t
inner   join   syscolumns   as   f
on   t.id   =   f.id
where   t.type= 'U '   and   lower(f.[name])   like   '%companycode '

OPEN   tableFieldCursor
FETCH   NEXT   FROM   tableFieldCursor
INTO   @tableName,   @fieldName
WHILE   @@FETCH_STATUS   =   0
BEGIN
exec( 'select   @tcount   =   count(d.code)   from   deleted   as   d   inner   join   '+   @tableName   + '   as   p   on   d.code=p. '   +   @fieldName)
if   @tcount   > 0
RAISERROR   ( '记录在使用中不能删除! ',   16,   1)
rollback   transaction
goto   quit

FETCH   NEXT   FROM   tableFieldCursor
INTO   @tableName,   @fieldName

END

quit:
CLOSE   tableFieldCursor
DEALLOCATE   tableFieldCursor

end

但是在删除记录时,触发器出错,提示“必须声明变量@tcount”,经查是exec语句出错,但不知道该如何写才对,请大家不吝赐教。

------解决方案--------------------
exec( 'select @tcount = count(d.code) from deleted as d inner join '+ @tableName + ' as p on d.code=p. ' + @fieldName)

直接写试试看
select @tcount = count(d.code) from deleted as d inner join ' '+ @tableName + ' ' as p on d.code=p. '[ '+@fieldName+ '] '
------解决方案--------------------
用法不正确:
CREATE TRIGGER [forbidToDeleteCompany] ON [dbo].[Company]
FOR DELETE
AS
begin

declare @tableName varchar(255)

declare @tcount int,@fieldName varchar(255),@tableName sysname,@sql nvarchar(1000)
DECLARE tableFieldCursor CURSOR FOR
select t.[name] as tableName,f.[name] as fieldName
from sysobjects as t
inner join syscolumns as f
on t.id = f.id
where t.type= 'U ' and lower(f.[name]) like '%companycode '

OPEN tableFieldCursor
FETCH NEXT FROM tableFieldCursor
INTO @tableName, @fieldName
WHILE @@FETCH_STATUS = 0
BEGIN
set @sql=N 'select @tcount = count(d.code)
from deleted as d inner join '+ @tableName + ' as p on d.code=p. ' + @fieldName
exec sp_executesql @sql,N '@tcount int output ',@tcount output
if @tcount > 0
RAISERROR ( '记录在使用中不能删除! ', 16, 1)
rollback transaction
goto quit

FETCH NEXT FROM tableFieldCursor
INTO @tableName, @fieldName

END

quit:
CLOSE tableFieldCursor
DEALLOCATE tableFieldCursor

end


------解决方案--------------------
貌似无法解决,
deleted表在EXEC中,可能不被认可