Try Catch Can't handle alter table

2019-09-20 12:47发布

问题:

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'

回答1:

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 SQL Server table



回答2:

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.