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?
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With