为什么触发器中的更新失败?

时间:2017-04-11 17:48:25

标签: sql-server

关于触发器应该如何工作,这里有很多答案但是我想知道我的独特之处在于代码在插入时运行但是@type变量得到了错误的答案。如果我与表引用隔离运行查询,我得到一个正确的答案返回;它只是作为触发器的一部分,我得到了错误。

查询的一部分调用一个函数但是这一切在隔离完成时都能正常工作,所以我想知道我的触发器中还有其他东西会导致它失败而我不知道吗?

SQL:

ALTER TRIGGER [dbo].[MPH_I_TEST_GROUP_REQUEST_PRINTS]
ON [dbo].[MPH_PRINT_TEST_QUEUE]
FOR INSERT,UPDATE
AS

DECLARE @V_Refno NUMERIC(10)
DECLARE @V_User_Modif VARCHAR(30)

BEGIN
SET @V_User_Modif = suser_sname()
SELECT  @V_Refno = tgreq_refno FROM inserted

--> Get details of test type
DECLARE @car_sponts VARCHAR(8000)
DECLARE @type VARCHAR(50)

SET @type = 'blank'
SELECT  @car_sponts = CONVERT(VARCHAR(8000),sypro.long_value)
FROM
    system_profiles sypro (NOLOCK)
WHERE
    sypro.code = 'MPH_CARD_PRT_SPONTS'
AND (sypro.archv_flag = 'N' OR sypro.archv_flag IS NULL)

--> Update type based on tests ordered
SELECT 
    @type = CASE WHEN COUNT(*) > 0 THEN 'CARDIO' ELSE 'type fail' END --> Does the request belong in a service point noted in system profile MPH_CARD_PRT_SPONTS
FROM    
    test_group_requests tgreq (NOLOCK)
INNER JOIN
    test_form_requests tfreq (NOLOCK) ON tgreq.tgreq_refno = tfreq.tgreq_refno
INNER JOIN
    test_requests tereq (NOLOCK) ON tfreq.tfreq_refno = tereq.tfreq_refno
INNER JOIN
    test_definitions tstdf (NOLOCK) ON tereq.tstdf_refno = tstdf.tstdf_refno
INNER JOIN
    test_locations tstlc (NOLOCK) ON tstlc.tstdf_refno = tstdf.tstdf_refno
WHERE   
    tgreq.tgreq_refno IN (SELECT tgreq_refno FROM inserted)
AND (tstlc.archv_flag = 'N' OR tstlc.archv_flag IS NULL)
AND tstlc.spont_refno IN
    (
    SELECT DISTINCT spont.spont_refno FROM service_points spont (NOLOCK) WHERE (spont.archv_flag = 'N' OR spont.archv_flag IS NULL) AND spont.code IN (SELECT Item FROM [dbo].[MPH_PARSELIST](@car_sponts))
    )

--> Update test type to print queue
UPDATE  mph_print_test_queue
SET mph_print_test_queue.type = 'updated ' + @type
FROM
    inserted,mph_print_test_queue
WHERE
    mph_print_test_queue.tgreq_refno = inserted.tgreq_refno

END

所以目前所有记录都会得到一种'更新类型失败',即使它们符合插入/更新'有氧'的标准。

提前致谢。 菲尔。

还尝试了此更新:

UPDATE  mph_print_test_queue
SET mph_print_test_queue.type = 'updated cardio'
FROM    
    inserted,test_group_requests tgreq (NOLOCK)
INNER JOIN
    test_form_requests tfreq (NOLOCK) ON tgreq.tgreq_refno = tfreq.tgreq_refno
INNER JOIN
    test_requests tereq (NOLOCK) ON tfreq.tfreq_refno = tereq.tfreq_refno
INNER JOIN
    test_definitions tstdf (NOLOCK) ON tereq.tstdf_refno = tstdf.tstdf_refno
INNER JOIN
    test_locations tstlc (NOLOCK) ON tstlc.tstdf_refno = tstdf.tstdf_refno
WHERE   
    tgreq.tgreq_refno = inserted.tgreq_refno
AND (tstlc.archv_flag = 'N' OR tstlc.archv_flag IS NULL)
AND tstlc.spont_refno IN
    (
    SELECT DISTINCT spont.spont_refno FROM service_points spont (NOLOCK) WHERE (spont.archv_flag = 'N' OR spont.archv_flag IS NULL) AND spont.code IN (SELECT Item FROM [dbo].[MPH_PARSELIST](@car_sponts))
    )

1 个答案:

答案 0 :(得分:0)

我终于在回家的路上得到了灯泡。不要将更新链接到插入的表,而只是根据匹配的记录批量更新。

很抱歉在发布之前没有收到此信息。漫长的一天。