存储过程中的SQL事务处理

时间:2014-06-03 11:27:02

标签: sql sql-server stored-procedures

我编写了一个存储过程来检查存储过程中事务的工作方式。

这是对的吗?我该如何检查这是否正确?

我想要做的是不删除第二个表数据;不应删除表数据。

CREATE PROCEDURE DeleteDepartment
(
   @DepartmentID    int
)
AS
   BEGIN TRANSACTION

   DELETE FROM Employees
   WHERE DepartmentID = @DepartmentID

   IF @@ERROR <> 0
   BEGIN
        -- Rollback the transaction
        ROLLBACK

        -- Raise an error and return
        RAISERROR ('Error in deleting employees in DeleteDepartment.', 16, 1)
        RETURN
   END

   DELETE FROM Departments
   WHERE DepartmentID = @DepartmentID

   IF @@ERROR <> 0
   BEGIN
       -- Rollback the transaction
       ROLLBACK

       -- Raise an error and return
       RAISERROR ('Error in deleting department in DeleteDepartment.', 16, 1)
       RETURN
   END

   COMMIT

3 个答案:

答案 0 :(得分:1)

CREATE PROCEDURE DeleteDepartment
(
   @DepartmentID    int
)
AS


BEGIN TRY 

BEGIN TRANSACTION

DELETE FROM Employees
WHERE DepartmentID = @DepartmentID

--Test Code Start
--For testing purpose Add an Insert statement with passing value in the identity column.
declare @table1 as table(ID Identity(1,1),Test varchar(10))

insert into @table1(ID, Test)
Values(1,'Failure Test')
--Test Code end

DELETE FROM Departments
WHERE DepartmentID = @DepartmentID


COMMIT TRANSACTION
END TRY

BEGIN CATCH
        ROLLBACK TRANSACTION
        RETURN ERROR_MESSAGE()
END CATCH

首先,Commit transaction出现在Rollback Transaction

之前

要测试事务是否有效,您可以做的是,尝试在2个删除语句之间的查询中添加INSERT语句,并尝试在其中添加标识列的值。这样第一次删除成功,但事务失败。现在,您可以检查第一次删除是否反映在表中。

答案 1 :(得分:0)

COMMIT应该在ROLLBACK之前。我建议使用try / catch块 它应该看起来像这样

BEGIN TRY
    declare @errorNumber as int
BEGIN TRANSACTION 

     --do 1st statement
     IF @@ERROR<>0
     BEGIN
       SET @errorNumber=1
     END

     --do 2nd statement
     IF @@ERROR<>0
     BEGIN
       SET @errorNumber=2
     END

 COMMIT

END TRY

BEGIN CATCH

    IF @@TRANCOUNT > 0

ROLLBACK

END CATCH

答案 2 :(得分:0)

您的存储过程可以正常工作,但我添加了几个位

CREATE PROCEDURE DeleteDepartment
(  @DepartmentID    int
)
AS

BEGIN TRANSACTION
BEGIN TRY
   DELETE FROM Employees 
   WHERE DepartmentID = @DepartmentID

   DELETE FROM Departments 
   WHERE DepartmentID = @DepartmentID

   COMMIT   
END TRY
BEGIN CATCH
   ROLLBACK

    -- Raise an error and return
    RAISERROR (ERROR_MESSAGE(), 16, 1)
END CATCH

END