7

I am trying to alter a table to add three new columns but I would like to check if the columns names before adding and if it already exists, just skip else add the column,

 ALTER TABLE TESTTABLE
 ADD [ABC] [int] ,
     [XYZ] [ [int] ,
     [PQR]  [int] 
GO

I have the below script

IF NOT EXISTS(
    SELECT *
    FROM sys.columns 
    WHERE Name      = N'ABC'
      AND Object_ID = Object_ID(N'TESTTABLE'))
BEGIN
    ALTER TABLE TESTTABLE
    ADD [ABC] int
END

but this has to be done for each column is there a better way to achieve this?

5
  • 2
    Are you looking to automate the creation of a table or just too lazy to look in SSMS / sys.columns? Commented Jul 15, 2016 at 16:10
  • I am trying to automate altering a table Commented Jul 15, 2016 at 16:11
  • 1
    Possible duplicate of How to check if a column exists in SQL Server table Commented Jul 15, 2016 at 16:12
  • Doing this completely in t-sql means you will have to do this one column at a time. Commented Jul 15, 2016 at 16:13
  • Need to write a userdefined function Commented Jul 15, 2016 at 16:41

2 Answers 2

5

If you're sure these columns will always and only be added together at the same time, you can use IN to check for existence of any and then add them all if none exist:

IF NOT EXISTS(
    SELECT *
    FROM sys.columns 
    WHERE Name IN (N'ABC',N'XYZ',N'PQR')
      AND Object_ID = Object_ID(N'TESTTABLE'))
BEGIN
    ALTER TABLE TESTTABLE
    ADD [ABC] int,
        [XYZ] int,
        [PQR] int
END

Do note that this will not execute if any one of your columns already exists. If there's a chance of that happening, you'll need to make each check individually as you're already doing.

Sign up to request clarification or add additional context in comments.

Comments

2

Simple and dirty, you use directly the column names in the condition with COL_LENGTH (which returns NULL if the column does not exist, i.e. "on error"):

DECLARE @tb varchar(30) = 'TESTTABLE'
IF  COL_LENGTH(@tb, 'ABC') IS NULL
AND COL_LENGTH(@tb, 'XYZ') IS NULL
AND COL_LENGTH(@tb, 'PQR') IS NULL
BEGIN
    ALTER TABLE TESTTABLE
    ADD [ABC] int, [XYZ] int, [PQR] int
END

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.