Try Catch Can't Handle Alter Table
Solution 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 a SQL Server table?
Specifically for your case,
IF COL_LENGTH('nyork', 'Qtr') ISNULLBEGINaltertable nyork
add [Qtr] varchar(20)
ENDSolution 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.
Solution 3:
You can wrap it with exec('alter goes here'). Then catch will catch
Solution 4:
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.
- Use dynamic SQL in the
TRYblock - It has been answered here. - Use stored procedure in the
TRYblock - Based on documentation.
Example based on your code:
DROPPROCEDURE IF EXISTS dbo.sp_my_proc
GO
CREATEPROCEDURE dbo.sp_my_proc
AS--Your original code here:ALTERTABLE nyork ADD [Qtr] VARCHAR(20)
GO
BEGIN TRY
EXECUTE dbo.sp_my_proc
--OptionalDROPPROCEDURE IF EXISTS dbo.sp_my_proc
END TRY
BEGIN CATCH
--Catch your error hereSELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
Post a Comment for "Try Catch Can't Handle Alter Table"