简体   繁体   中英

Try Catch Can't handle alter table

Why I this can't handle the alter table?

Begin Try
alter table nyork add [Qtr] varchar(20)
End Try
Begin Catch
Print 'Column already exist'
End Catch'

Because one of them is a transact sql command (the try catch) and the other is a DDL statement.

You'd probably do better off querying to see if the column exists before doing the alter statement.

To do this with MSSQL, see How to check if a column exists in a SQL Server table?

Specifically for your case,

IF COL_LENGTH('nyork', 'Qtr') IS NULL
BEGIN
    alter table nyork
    add [Qtr] varchar(20)
END

You cannot do such a thing. TRY...CATCH can only handle runtime errors. Your script will run as long as the column does not exist but not when it is already there. The name resolution of the objects is done at compile time. Therefore SQL Server will always recognize the missing column before it starts any execution. For that reason, you can't also do such a thing with dynamic SQL.

You can wrap it with exec('alter goes here'). Then catch will catch

As @Marcus Vinicius Pompeu said: "You'd probably do better off querying to see if the column exists before doing the alter statement."

But , if you really want to use TRY...CATCH with DDL . There is two way for do this.

  1. Use dynamic SQL in the TRY block - It has been answered here .
  2. Use stored procedure in the TRY block - Based on documentation .

Example based on your code:

DROP PROCEDURE IF EXISTS dbo.sp_my_proc
GO
CREATE PROCEDURE dbo.sp_my_proc
AS
    --Your original code here:
    ALTER TABLE nyork ADD [Qtr] VARCHAR(20)
GO

BEGIN TRY  
    EXECUTE dbo.sp_my_proc 
    --Optional
    DROP PROCEDURE IF EXISTS dbo.sp_my_proc
END TRY  
BEGIN CATCH  
    --Catch your error here
    SELECT   
        ERROR_NUMBER() AS ErrorNumber  
        ,ERROR_MESSAGE() AS ErrorMessage;  
END CATCH; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM