SQL打印错误消息与错误的记录代码

时间:2013-08-29 13:03:43

标签: sql printing triggers declare

使用SQL Server 2005 创建触发器,检查插入是否已存在。 获取记录参数时遇到问题,有代码:

CREATE TRIGGER t_MFShiftTypeOperation ON [CAST$MFShiftTypeOperation]
    FOR INSERT, UPDATE AS

IF @@ ROWCOUNT = 1 开始

IF EXISTS (SELECT * FROM inserted AS I
           JOIN CAST$MFShiftTypeOperation AS STO
           ON ((I.ShiftTypeCode = STO.ShiftTypeCode AND 
                I.PackCode = STO.PackCode) OR
                I.RegisterAppCode = STO.RegisterAppCode))
BEGIN

    DECLARE @Bad_PackCode AS EmpUserCode_t
    SET @Bad_PackCode = SELECT TOP(1) PackCode FROM inserted --there is error

    ROLLBACK TRAN
    PRINT  'Оperation with '+ @Bad_PackCode +' already exist'
END

END

当我尝试执行代码时,它会抛出错误消息:

 Msg 156, Level 15, State 1, Procedure t_MFShiftTypeOperation, Line 16
Incorrect syntax near the keyword 'SELECT'.

有人可以解释哪里出错,或建议更好的解决方案。

1 个答案:

答案 0 :(得分:0)

更改此行:

SET @Bad_PackCode = SELECT TOP(1) PackCode FROM inserted --there is error

到此:

SELECT TOP(1) @Bad_PackCode=PackCode FROM inserted