Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
beatkeeper25
Starting Member
27 Posts |
Posted - 2013-09-10 : 22:01:15
|
I've come across a sproc that is supposed to create columns if they don't exist. Author used Try Catch, but its not working right.BEGIN TRYSELECT TOP 1 Column1 FROM TableAEND TRYBEGIN CATCHALTER TABLE TableA ADD Column1END CATCH I'm trying this approach, but would like it not to throw any errors if the column exists.IF NOT EXISTS ( SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'TableA') AND name = 'Column1') BEGIN ALTER TABLE TableA ADD Column1 INT NOT NULL ENDWhat's the best way to accomplish this? |
|
tkizer
Almighty SQL Goddess
38200 Posts |
|
beatkeeper25
Starting Member
27 Posts |
Posted - 2013-09-11 : 00:14:09
|
Can TRY CATCH be used this way? |
|
|
bandi
Master Smack Fu Yak Hacker
2242 Posts |
Posted - 2013-09-11 : 00:41:33
|
As per my point of view, 2nd approach is the best way--Chandu |
|
|
Lumbago
Norsk Yak Master
3271 Posts |
Posted - 2013-09-11 : 03:43:51
|
This would be the best:IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TableA' AND COLUMN_NAME = 'Column1') ALTER TABLE TableA ADD Column1 INT NOT NULL - LumbagoMy blog-> http://thefirstsql.com |
|
|
|
|
|