Diff two tables in SQL Server and generate DML to adjust the one
-
30-09-2019 - |
Question
I have two tables; one is an older version of the second. I'd like to add the fields from the new one to the second one. Is there an easy way to do this without manually parsing out the fields (there are many)?
Again, I'm just adding fields, so I won't have to remove any data from the older table when I make it current.
Thanks!
PS SQL Server 2005.
Solution
This will show columns in Table1
that aren't in Table2
.
SELECT *
FROM syscolumns
WHERE ID = Object_ID('Table1') Name Not IN (SELECT Name from sysColumns where ID = Object_ID('Table2'))
Taking the name, length, xtype and other fields from syscolumns
to turn it into DDL statement is pretty easy
SELECT 'alter table table2 add column ' + name + ' '+ type_name(xtype ) + etc, etc
FROM syscolumns
WHERE ID = Object_ID('Table1') Name Not IN (SELECT Name from sysColumns where ID = Object_ID('Table2'))
OTHER TIPS
Yes there is a tool tablediff.exe link text or Microsoft Technet
- Here is a tool that does it.
This is a query that will list the columns for a table:
SELECT *
FROM syscolumns
WHERE Id IN (SELECT ID from sysobjects WHERE name = 'TABLENAME')
Run the query for both tables, filter out the UNION
, and you at least have a punchlist.