Thursday, November 24, 2005

Post Structure Alteration

I was given to do alter the structure of a database according to another one And I’ve finished writing all the scripts to turn the database B into A . But what if the database A has been altered meanwhile ? This is very annoying because constantly i have to modify the scripts in order to keep up with database A alteration. I order not to do that i had to write a small script that ad's automatically the new objects from the database A ... and there it is (for now it can only add columns but i will do it in order to add tables , triggers , stored procedures , Constraints, Indexes etc ....and even the actual data . ****************************************************************************
declare mycursor cursor
for select x1.name , x2.name , x3.name , x1.length , x1.isnullable
from [Server1].[database A].[dbo].[syscolumns] x1
inner join [Server1 ].[DataBase A].[dbo].[sysobjects] x2 on x2.id = x1.id
inner join [Server1].[DataBase A].[dbo].[systypes] x3 on x3.xtype = x1.xtype
inner join sysobjects x4 on x4.name = x2.name
where x2.xtype= 'U' and x1.name not in (select name from syscolumns)
declare @Col sysname
declare @Tab sysname
declare @Type sysname
declare @Length varchar(100)
declare @Null smallint
declare @SQL varchar(1000)
open mycursor
fetch next from mycursor into @Col , @Tab , @Type , @Length , @Null
while @@fetch_status =0
begin
SET @SQL = case when @Null =0 then 'alter table ' + @Tab + ' add ' + @Col + ' '
+ @Type + case when charindex('char', @Type) > 0 then '(' + @Length + ')'
else '' end + ' not null '
else 'alter table ' + @Tab + ' add ' + @Col + ' '
+ @Type + case when charindex('char', @Type) > 0 then '(' +
@Length + ')' else '' end + ' null '

end Exec(@SQL)
fetch next from mycursor into @Col , @Tab , @Type , @Length , @Null
end
close mycursor
deallocate mycursor *********************************************************************************** P.S. If the 2 databases are not on the same server you must link the servers (run SP_LinkedServers '[Server A]' , '[Server B]'

0 Comments:

Post a Comment

<< Home