急求触发器解答

idot idot 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我刚开始用触发器,请向大家请教一个问题:我写了一个触发器如下:
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语句出错,但不知道该如何写才对,请大家不吝赐教。
...全文

相关推荐

评论 7
收藏 已收藏
分享
返回顶部
idot
MS-SQL Server 34,876 成员 254,635 内容