How to trap errors in SQL Scripts

Jeff Stiegler 466 Reputation points
2022-05-13T14:02:35.21+00:00

We use scripts to add columns to our data tables like the one below. If the column already exists in the table, then the script crashes. Is there a way to trap this error so that script does not crash?

/* Add new column to dbo.cldoctype */
set xact_abort on
begin transaction

ALTER TABLE cldoctype ADD packet varchar(10) NULL

commit transaction
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,714 questions
0 comments No comments
{count} votes

Accepted answer
  1. Naomi 7,361 Reputation points
    2022-05-13T14:12:24.79+00:00

    Try the following:

    begin transaction
    if not exists (select 1 from INFORMATION_SCHEMA.Columns where table_schema = 'dbo' and table_name='clDocType' and column_name = 'packet') -- check for column's existence
    
           ALTER TABLE cldoctype ADD packet varchar(10) NULL
    
     commit transaction
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jeff Stiegler 466 Reputation points
    2022-05-13T14:27:28.403+00:00

    NaomiNNN,

    I copied and pasted your code into my SSMS and received two errors: schema_name - Invalid column name 'schema_name' and 1. - Incorrect syntax near '1.'

    How do I fix this?