每个存储过程如果涉及到2个以上的数据更新操作,通常我们会采用 TRANSCTION 来做事务性操作。但一旦遇到存储过程之间的调用时,举个例子:A存储过程调用B存储过程。会遇到A存储过程的事务不受B存储过程事务影响的问题,通常很多人的做法是检查B存储过程的ReturnValue,如果返回值不为0,则代表出错,存储过程A执行相应的操作。
应该采用下面的方法:
DECLARE @ErrorCode int
SET @ErrorCode = 0
DECLARE @TranStarted bit
SET @TranStarted = 0
IF( @@TRANCOUNT = 0 )
BEGIN
BEGIN TRANSACTION
SET @TranStarted = 1
END
ELSE
SET @TranStarted = 0
-- 需要考虑原子性的存储过程语句写在这里
-- 先检查 UserSectionProfile中是否已经存在该用户的信息记录
IF EXISTS(SELECT UserName FROM UserSectionProfiles WHERE UserName = @UserName AND SectionID = @SectionID)
BEGIN
-- 更新UserSectionProfile
UPDATE UserSectionProfile
SET
SectionCardXml = @SectionCardXml,
LastUpdatedDate = @CurrentTime
WHERE
UserName = @UserName AND
SectionID = @SectionID
END
ELSE -- 否则创建UserSectionProfile
BEGIN
-- 写入UserSectionProfile
INSERT INTO UserSectionProfiles(UserName,SectionID,SectionCardXml, CreatedDate,LastUpdatedDate)
VALUES(@UserName,@SectionID,@SectionCardXml,@CurrentTime,@CurrentTime)
END
IF( @@ERROR <> 0 )
BEGIN
SET @ErrorCode = -1
GOTO Cleanup
END
IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
COMMIT TRANSACTION
END
RETURN 0
Cleanup:
IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
ROLLBACK TRANSACTION
END
RETURN @ErrorCode