更改SQL Server事务中的表

时间:2010-07-30 10:05:43

标签: sql-server-2005 transactions alter-table

我正在尝试编写此事务,我正在尝试使用TRY..CATCH和TRANSACTION向表中添加列。这是我的代码。但问题是表中的列已经存在并且catch块应该执行,但catch块没有执行,并且事务没有被回滚,并且select error_number语句也没有执行。

BEGIN TRY
    BEGIN TRANSACTION;
        ALTER TABLE ONADJ ADD BR_INIT CHAR (3) NULL REFERENCES BRANCH(BR_INIT)
    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ERRORNUMBER,ERROR_MESSAGE() AS ERRORMESSAGE;

    IF (XACT_STATE()) = -1
    BEGIN
        PRINT
            N'THE TRANSACTION IS IN AN UNCOMMITTABLE STATE. ROLLING BACK TRANSACTION.'
        ROLLBACK TRANSACTION;
    END;

    IF (XACT_STATE()) = 1
    BEGIN
        PRINT
            N'THE TRANSACTION IS COMMITTABLE. COMMITTING TRANSACTION.'
        ROLLBACK TRANSACTION;   
    END;
END CATCH

2 个答案:

答案 0 :(得分:3)

不是使用事务并期望TRY CATCH工作,更好的选择是检查表中是否存在列,如果不存在,则使用下面给出的alter query -

if Not Exists(select * from sys.columns where Name = N'columnName'   
                and Object_ID = Object_ID(N'tableName')) 

begin 

-- Your alter statement

end 

答案 1 :(得分:3)

使用作为跨数据库标准的Information_Schema对象,而不是使用sys.columns。语法也更简单,更容易记住:

If Not Exists (Select * From Information_Schema.Columns
  Where Table_Schema = 'SchemaName' -- or dbo if you aren't using schemas
  And Table_Name = 'TableName'
  And Column_Name = 'ColumnName'))

Begin

-- Your alter statement

End