用于启动外部脚本文件的SQL Server触发器

时间:2016-05-11 14:49:55

标签: sql sql-server-2008 triggers

我写了一个触发器,在更新或插入时启动脚本。但是当触发器运行时,它最终会锁定我的数据库,我必须重新启动才能再次运行查询。我没有在触发器中看到任何会导致这种情况的东西。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[CALCULATEDFIELDS]
ON  [dbo].[custom_values]
AFTER INSERT, UPDATE
AS 
    SET NOCOUNT ON;

    DECLARE @CUSTOMIZED_ID VARCHAR(15)

    SELECT @CUSTOMIZED_ID = (SELECT customized_id FROM inserted)

    BEGIN
        DECLARE @OUTSTRING varchar(300)

        BEGIN
            IF NOT @CUSTOMIZED_ID IS NULL
                SELECT @OUTSTRING = '\\DRIVE\Folder\Script.vbs '+ @CUSTOMIZED_ID
            ELSE
                SELECT @OUTSTRING = '\\DRIVE\Folder\Script.vbs '+ @CUSTOMIZED_ID

            EXEC master..xp_cmdshell @OUTSTRING, NO_OUTPUT
        END
    END

1 个答案:

答案 0 :(得分:0)

以下陈述没有任何意义:

SELECT @CUSTOMIZED_ID = (SELECT customized_id FROM inserted)

实际上最终会出现这样的错误:

Msg 512, Level 16, State 1, Line 6
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

这种方式应该更有意义(因为您的customize_id始终是相同的):

SELECT TOP 1 @CUSTOMIZED_ID = customized_id FROM inserted

解决你的“阻塞”问题:

您是否尝试在不启动脚本的情况下运行更新(和触发器)?

-- EXEC master..xp_cmdshell @OUTSTRING, NO_OUTPUT

您的更新有效吗?如果是,看起来您的脚本执行时间过长或者您遇到任何其他问题。您的脚本在更新后是否会执行?你检查过了吗?

此外,您为什么要这样做?无论如何你都会调用脚本,或者我错了?

IF NOT @CUSTOMIZED_ID IS NULL