嵌套存储过程和事务范围

时间:2013-04-10 20:16:21

标签: sql-server-2008 stored-procedures scope

我有一个主要的工作程序和一个附带的记录程序。我正在寻找关于我对sql server 2008的假设的验证。期望的结果是SP1执行它可以做的任何工作并且在记录进度的过程中调用SP2。无论SP1是否遇到会导致其事务回滚的错误,都会提交SP2工作。

我看起来安全吗?我是否需要以不同的方式命名SP2中的事务?

------------------------------------------------------- SP1 pseudocode
BEGIN TRY
    BEGIN TRANSACTION

    -- Do stuff
    -- log progress
    exec SP2( getutcdate(), 'source_is_sp1','message for progress');

    -- Do more stuff
    -- log progress
    exec SP2( getutcdate(), 'source_is_sp1','message for progress');

    -- etc

    COMMIT TRANSACTION
    RETURN 0
END TRY
BEGIN CATCH
    -- error handling not important
    ROLLBACK TRANSACTION
    return @StepNumber -- not important 
END CATCH


------------------------------------------------------- SP2

CREATE PROCEDURE [dbo].[SP2]

    @Source as nvarchar(100),
    @Timestamp as datetime,
    @Message as nvarchar(4000)

AS
BEGIN
    SET NOCOUNT ON;

    IF @Timestamp is null
    BEGIN
        set @Timestamp = GETUTCDATE();
    END

    IF @Source IS NOT NULL AND @Message IS NOT NULL
    BEGIN
        BEGIN TRANSACTION;
            INSERT INTO LOG(LOGTIMESTAMP, SOURCEVCH, MESSAGEVCH) 
                    VALUES (@Timestamp, @Source, @Message);
        COMMIT TRANSACTION;
    END
END

0 个答案:

没有答案