Avatar of brgdotnet
brgdotnet
Flag for United States of America asked on

Best code for creating a new column

I have two different blocks of sql code which basically perform the same functionality. One queries SYS.COLUMNS and the other queries
INFORMATION_SCHEMA.COLUMNS.
Which query is better to use, #1 or #2 ? Also ignore the fact that the second query uses parameters for the table name and column name instead of the hard coding which occurs in #1.


(1)
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Name = N'ROTOCOST' AND Object_ID = Object_ID())
                  BEGIN
                        EXEC('ALTER TABLE CUSTOMERS ADD ROTOCOST CHAR(9)')
                  END




(2)
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = @NewColName AND TABLE_NAME =  @TableName)
                        BEGIN
                              SET @sql = 'ALTER TABLE ' + @TableName + ' ADD ' +  @NewColName + ' ' + ' CHAR(9) '
                              EXEC(@sql)
                        END
Microsoft SQL Server

Avatar of undefined
Last Comment
brgdotnet

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
chaau

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
Vitor Montalvão

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
brgdotnet

ASKER
Thank you.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes