2

我正在尝试编写此事务,我正在尝试使用 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
4

2 回答 2

4

而不是使用事务并期望 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 
于 2010-07-30T10:22:49.240 回答
3

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

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
于 2012-03-28T15:00:55.147 回答