SQL在try catch块中重新执行存储过程

时间:2012-02-08 16:11:56

标签: sql stored-procedures merge try-catch

我有一个正在进行MERGE的存储过程。似乎给定了流量,两个请求同时调用INSERT而不是UPDATE。由于外键约束,其中一个请求失败。如果我将我的merge语句放在try catch中并尝试重新执行sproc,我假设它将在这次运行MERGE的UPDATE部分并成功。对此的想法,是否被认为是好/坏的做法?

如果重要的话,我正在使用SQL Server 2008.

提前欢呼

2 个答案:

答案 0 :(得分:0)

您可以在try / catch块中复制它,但更好的解决方案可能是在并发运行时解决锁定问题。在合并声明之前,实现类似内容的规范方法如下:

BEGIN TRANSACTION;

UPDATE dbo.Table WITH (HOLDLOCK)
SET Col = @Val
WHERE Key= @Something;

IF @@ROWCOUNT = 0
  INSERT INTO dbo.TABLE (Key, Col) VALUES (@Key, @Val);

COMMIT TRANSACTION;

因此,对于MERGE,我建议您执行以下操作:

MERGE dbo.Table WITH (HOLDLOCK) ...

我还建议使用http://www.datamanipulation.net/sqlquerystress/

测试并发性

答案 1 :(得分:0)

-- Verify that the stored procedure does not already exist.


IF OBJECT_ID ( 'usp_GetErrorInfo', 'P' ) IS NOT NULL 
    DROP PROCEDURE usp_GetErrorInfo;
GO

-- Create procedure to retrieve error information.
CREATE PROCEDURE usp_GetErrorInfo
AS
SELECT
    ERROR_NUMBER() AS ErrorNumber
    ,ERROR_SEVERITY() AS ErrorSeverity
    ,ERROR_STATE() AS ErrorState
    ,ERROR_PROCEDURE() AS ErrorProcedure
    ,ERROR_LINE() AS ErrorLine
    ,ERROR_MESSAGE() AS ErrorMessage;
GO

BEGIN TRY
    -- Generate divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    -- Execute error retrieval routine.
    EXECUTE usp_GetErrorInfo;
END CATCH;