Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a column if it doesn't exist to all tables?

I'm using SQL Server 2005/2008. I need to add a column to a table if it does not yet exist. This will apply to all tables in a given database. I hoped I was close, but I'm having issues with this solution.

How can this be done?

Here's what I have:

EXEC sp_MSforeachtable '     declare @tblname varchar(255);     SET @tblname =  PARSENAME("?",1);      if not exists (select column_name from INFORMATION_SCHEMA.columns                     where table_name = @tblname and column_name = ''CreatedOn'')      begin         ALTER TABLE @tblname ADD CreatedOn datetime NOT NULL DEFAULT getdate();     end ' 

But I get errors:

Error 102: Incorrect syntax near '@tblname'. Incorrect syntax near 'CreatedOn'. Incorrect syntax near '@tblname'. Incorrect syntax near 'CreatedOn'. ... and so on, for each table.

like image 859
Scott Stafford Avatar asked Feb 28 '11 18:02

Scott Stafford


People also ask

How do I add one column to all tables in SQL?

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. The ALTER TABLE statement is also used to add and drop various constraints on an existing table.

How do you check if a column exists in multiple tables?

The easiest and straightforward way to check for the column in a table is to use the information schema for column system view. Wright a select query for INFORMATION_SCHEMA. COLUMNS as shown below. If the query returns record, then the column is available in the table.


1 Answers

You cannot use variables, like @tableName, in DDL. Besides, splinting the name into part and ignoring the schema can only result in bugs. You should just use the ''?'' replacement in the SQL batch parameter and rely on the MSforeachtable replacement:

EXEC sp_MSforeachtable ' if not exists (select * from sys.columns                 where object_id = object_id(''?'')                and name = ''CreatedOn'')  begin     ALTER TABLE ? ADD CreatedOn datetime NOT NULL DEFAULT getdate(); end'; 
like image 145
Remus Rusanu Avatar answered Oct 04 '22 05:10

Remus Rusanu