即使发生错误也执行语句

时间:2014-04-08 13:33:02

标签: sql sql-server sql-server-2012

我有这个SQL Server 2012快速存储过程:

CREATE PROCEDURE GetNewCodes
    @gintNewCodes bigint,   
    @presNewCodes tinyint,
    @levelNewCodes bigint,
    @quantityNewCodes smallint
AS

-- Get new codes from INCIC database.
DECLARE @return_value int,
        @xmlGenerated xml,
        @xmlString NVARCHAR(MAX)

SET NOCOUNT ON;

    -- Set that this stored procedure is running
    update dbo.RunningSPs with (serializable) set conf_value = 1
    where sp_name = N'GetNewCodes'

    if @@rowcount = 0
    begin
        insert dbo.RunningSPs(sp_name, conf_value) values (N'GetNewCodes', 1)
    end

EXEC    @return_value = [INCIC].[dbo].[ReadCodeBuffer]
        @gint = @gintNewCodes,
        @pres = @presNewCodes,
        @level = @levelNewCodes,
        @quantity = @quantityNewCodes,
        @xmlGenerated = @xmlGenerated OUTPUT

SET @xmlString = cast(@xmlGenerated as nvarchar(max))

EXEC dbo.ProcessCodes @XmlString = @xmlString

    update dbo.RunningSPs with (serializable) set conf_value = 0
    where sp_name = N'GetNewCodes'

GO

我想要执行这个:

    update dbo.RunningSPs with (serializable) set conf_value = 0
    where sp_name = N'GetNewCodes'

即使我收到错误。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

使用

BEGIN TRY

    -- Actual code gets here

END TRY
BEGIN CATCH

    -- Log error (if case)

END CATCH

-- Always executing code
update dbo.RunningSPs with (serializable) set conf_value = 0
where sp_name = N'GetNewCodes'

答案 1 :(得分:0)

如果语句创建错误,则无法执行语句。如果在TRY CATCH块中包装语句,它将捕获错误,但语句的执行将被中断

例如以下两个代码块。第一个不会返回任何内容,但第二个将返回5并且还会PRINT消息。

BEGIN TRY
SELECT 5/0
PRINT 'Do something'
END TRY
BEGIN CATCH
END CATCH

BEGIN TRY
SELECT 5/1
PRINT 'Do something'
END TRY
BEGIN CATCH
END CATCH