I'm working with two tables in SQL Server 2008: foo
and foo_mod
which have the following schema:
CREATE TABLE foo
(
[bar] DATETIME NULL ,
[bar1] VARCHAR(20) NULL ,
[different_column] VARCHAR(50) NOT NULL
)
CREATE TABLE foo_mod
(
[bar] DATETIME NULL ,
[bar1] VARCHAR(20) NULL
)
I'd like to build a SQL script that makes the following:
For each column of foo
check if that column exists in foo_mod
, if not, alter foo_mod
in order to add the missing column.
In this example my script will return the following:
IF COL_LENGTH('foo_mod','bar') IS NULL BEGIN
ALTER TABLE foo_mod
ADD bar DATETIME NULLL;
END
IF COL_LENGTH('foo_mod','bar1') IS NULL BEGIN
ALTER TABLE foo_mod
ADD bar1 VARCHAR(20) NULL;
END
IF COL_LENGTH('foo_mod','different_column') IS NULL BEGIN
ALTER TABLE foo_mod
ADD different_column VARCHAR(50) NOT NULL;
END
Now my script use a cursor to loop through the INFORMATION_SCHEMA.COLUMNS
from first table:
DECLARE @column_name VARCHAR(max);
DECLARE @is_nullable VARCHAR(3);
DECLARE @data_type NVARCHAR(128);
DECLARE @default NVARCHAR(4000);
DECLARE @max_lengh INT;
DECLARE @sql VARCHAR(max);
DECLARE @output VARCHAR(max);
SET @output = '';
DECLARE col_names_cursor CURSOR
FOR
SELECT COLUMN_NAME, IS_NULLABLE, DATA_TYPE, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'foo'
OPEN col_names_cursor
FETCH NEXT FROM col_names_cursor INTO @column_name, @is_nullable, @data_type,@default, @max_lengh;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'IF COL_LENGTH(''foo_mod'','''@column_name''') IS NULL BEGIN ALTER TABLE ''foo_mod'' ADD '
SET @sql += ? -- build sql script from informations
FETCH NEXT FROM col_names_cursor INTO @column_name, @is_nullable, @data_type,@default, @max_lengh;
END
CLOSE col_names_cursor;
DEALLOCATE col_names_cursor;
Is there an easy way to build the SQL statement from the informations given?
Thanks!