Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a column exists before adding the column to SQL table without altering table for each column

Tags:

sql-server

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?

like image 566
DoIt Avatar asked Jul 15 '16 16:07

DoIt


People also ask

How do you check if a column exists in SQL table?

Checking Existence of the Column: For checking the existence we need to use the COL_LENGTH() function. COL_LENGTH() function returns the defined length of a column in bytes. This function can be used with the IF ELSE condition to check if the column exists or not.

How do you check if a column value exists in another column in SQL?

How can I check if one column value is present in another column in SQL? Example using VLOOKUP You can check if the values in column A exist in column B using VLOOKUP. Select cell C2 by clicking on it. Insert the formula in “=IF(ISERROR(VLOOKUP(A2,$B$2:$B$1001,1,FALSE)),FALSE,TRUE)” the formula bar.


1 Answers

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.

like image 97
Kenbo Avatar answered Nov 15 '22 05:11

Kenbo