SQL触发器抛出错误

时间:2012-04-16 09:26:23

标签: sql-server-2008 email triggers alert procedure

ALTER TRIGGER [dbo].[AlertMail_tr]
ON 
[dbo].[MethodToLog_tbl]
AFTER INSERT 
AS      
BEGIN
DECLARE @LogId int
SET @LogId = (SELECT LogDataId FROM inserted)
if(SELECT Failure_flag FROM inserted)=1
begin
        exec [DB].[dbo].SendMail_prc
        @Command='EXEC CheckNew.dbo.FailureMail_prc @LogId'
        ,@MailPriority=1
        ,@MailRecipients='abc@xyz.com'
        ,@Subject='Alert-Failure'

end
END

我收到此错误:

  

必须声明标量变量@LogId。

2 个答案:

答案 0 :(得分:2)

@Command='EXEC CheckNew.dbo.FailureMail_prc @LogId='+cast ( @LogId as nvarchar(100))

@Command='EXEC CheckNew.dbo.FailureMail_prc '+cast ( @LogId as nvarchar(100))

另外,

@LogId 之前将放在之前执行字符串查询。

修改

declare @tmp nvarchar(max)
set @tmp='EXEC CheckNew.dbo.FailureMail_prc '+cast (@LogId as nvarchar(100))



 exec [DB].[dbo].SendMail_prc
        @Command=@tmp
        ,@MailPriority=1
        ,@MailRecipients='abc@xyz.com'
        ,@Subject='Alert-Failure'

答案 1 :(得分:0)

您的@LogId变量在EXEC命令的范围内不存在。 它只看到里面的内容,所以就音乐会而言,DECLARE @LogId int行不存在。

您需要传递已经包含变量值的字符串。

declare @aux varchar(100)
set @aux ='EXEC CheckNew.dbo.FailureMail_prc '+cast ( @LogId as varchar(10)) 

        exec [DB].[dbo].SendMail_prc
        @Command=@aux
        ,@MailPriority=1
        ,@MailRecipients='abc@xyz.com'
        ,@Subject='Alert-Failure'

当然,根据需要更正长度