Try Catch Can't handle alter table

2019-09-20 12:27发布

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'

2条回答
神经病院院长
2楼-- · 2019-09-20 13:00

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

查看更多
狗以群分
3楼-- · 2019-09-20 13:14

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.

查看更多
登录 后发表回答