Solved

Database Table  Compare - SQL SERVER

Posted on 2012-03-21
13
366 Views
Last Modified: 2012-04-05
I need to do a (Table to Table) compare in two different databases on the same server.

I need to find the differences between any given set of two tables with the same name in two different databases.   I can not use a third party tool, need a script based solution possibly from the DMVs sysobjects, syscolumns etc....
0
Comment
Question by:JGH5
  • 4
  • 3
  • 3
  • +2
13 Comments
 
LVL 12

Expert Comment

by:NormanMaina
Comment Utility
You can use the tablediff utility.

http://msdn.microsoft.com/en-us/library/ms162843.aspx
0
 

Author Comment

by:JGH5
Comment Utility
Thanks Norman, However, I need a Schema Compare not a Data Compare.  Need to see if Columns are missing or if the Data Types are different when they should all be the same.
0
 
LVL 16

Expert Comment

by:DcpKing
Comment Utility
This code will list you the columns, types, etc. in a table.

select column_name=syscolumns.name,
         datatype=systypes.name,
         length=syscolumns.length
    FROM sysobjects
    JOIN syscolumns ON sysobjects.id = syscolumns.id
    JOIN systypes ON syscolumns.xtype=systypes.xtype
where sysobjects.name = YOUR TABLE NAME HERE'
and sysobjects.xtype='U'
ORDER BY syscolumns.name
0
 
LVL 12

Expert Comment

by:NormanMaina
Comment Utility
If you are a developer and have access to VS 2011 ,you can use it to compare and sync schemas.
http://msdn.microsoft.com/en-us/library/dd193250.aspx

Or you can use this free tool:
http://www.sqleffects.com/Articles/Product/sqlAccordInfo/aboutSqlAccordCommunityEd.html
0
 
LVL 25

Expert Comment

by:TempDBA
Comment Utility
Use sql compare by Redgate. A very helfpul tool.
0
 
LVL 69

Expert Comment

by:ScottPletcher
Comment Utility
Does that give you what you need, or would you prefer an actual script, as orig stated?
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 

Author Comment

by:JGH5
Comment Utility
An actual script is preferred since I do not have access to any of the mainstream tools.
0
 
LVL 16

Expert Comment

by:DcpKing
Comment Utility
Do you need more details than in than the script I provided above? You can easily create a tablevar with two lots of fields and fill one lot with the results from one run (on one table) of this code and the other lot with the results from another run (on a different table) of this code. Then select all from the tablevar to see differences immediately
0
 
LVL 69

Expert Comment

by:ScottPletcher
Comment Utility
Working on a full script now, please just give me a little time :-) .
0
 
LVL 16

Expert Comment

by:DcpKing
Comment Utility
Go for it Scott! I'm actually in work, so don't have the time for that :)
0
 
LVL 69

Accepted Solution

by:
ScottPletcher earned 500 total points
Comment Utility
Please try this and let me know what adjustments are needed :-) ::


DECLARE @db1 sysname
DECLARE @table1 sysname
DECLARE @db2 sysname
DECLARE @table2 sysname

SET @db1 = '<db1_name>'          --will default to current db if NULL/''
SET @db2 = '<db2_name>'          --will default to current db if NULL/''
SET @table1 = '<table1_name>'  --will default to @table2 if NULL/''; may include schema. if needed
SET @table2 = NULL                  --will default to @table1 if NULL/''; may include schema. if needed


--**************************************************************************************************

DECLARE @sql nvarchar(max)
DECLARE @schema1 sysname
DECLARE @schema2 sysname

IF @db1 IS NULL OR @db1 = ''
    SET @db1 = DB_NAME()
IF @table1 IS NULL OR @table1 = ''
    SET @table1 = @table2
IF @db2 IS NULL OR @db2 = ''
   SET @db2 = DB_NAME()
IF @table2 IS NULL OR @table2 = ''
    SET @table2 = @table1
   
SET @schema1 = PARSENAME(@table1, 2)
SET @table1 = PARSENAME(@table1, 1)
IF @schema1 IS NULL
    SET @schema1 = 'dbo'    
SET @schema2 = PARSENAME(@table2, 2)
SET @table2 = PARSENAME(@table2, 1)
IF @schema2 IS NULL
    SET @schema2 = 'dbo'
   
--SELECT @db1, @db2, @table1, @table2, @schema1, @schema2

SET @sql = '
SELECT
    ColumnName,
    CASE WHEN [Datatype1] <> [Datatype2] THEN ''Yes'' ELSE ''No'' END AS [Datatype Diff?],
    [$db1$?], [$db2$?],
    [Datatype1], [Datatype2],
    [Nullable?], [Identity?], [Computed?]
FROM (
SELECT
    COALESCE(c1.name, c2.name) AS ColumnName,    
    CASE WHEN c1.name IS NULL THEN ''No'' ELSE ''Yes'' END AS [$db1$?],
    CASE WHEN c2.name IS NULL THEN ''No'' ELSE ''Yes'' END AS [$db2$?],
    COALESCE(t1.name + CASE
        WHEN t1.name LIKE ''%bin%'' OR t1.name LIKE ''%char%''  THEN ''('' +
            CASE WHEN t1.max_length = -1 THEN ''MAX'' ELSE CAST(t1.max_length AS varchar(10)) END + '')''
        WHEN t1.name IN (''decimal'', ''numeric'')  THEN ''('' +
            CAST(t1.precision AS varchar(10)) + '','' + CAST(t1.scale AS varchar(10)) + '')''
        WHEN t1.name IN (''float'', ''real'')  THEN ''('' +
            CAST(t1.precision AS varchar(10)) + '')''
        ELSE ''''
        END, ''-'') AS [Datatype1],
    COALESCE(t2.name + CASE
        WHEN t2.name LIKE ''%bin%'' OR t2.name LIKE ''%char%''  THEN ''('' +
            CASE WHEN t2.max_length = -1 THEN ''MAX'' ELSE CAST(t2.max_length AS varchar(10)) END + '')''
        WHEN t2.name IN (''decimal'', ''numeric'')  THEN ''('' +
            CAST(t2.precision AS varchar(10)) + '','' + CAST(t2.scale AS varchar(10)) + '')''
        WHEN t2.name IN (''float'', ''real'')  THEN ''('' +
            CAST(t2.precision AS varchar(10)) + '')''
        ELSE ''''
        END, ''-'') AS [Datatype2],
    COALESCE(CAST(c1.is_nullable AS char(1)), ''-'') + '' / '' + COALESCE(CAST(c2.is_nullable AS char(1)), ''-'') AS [Nullable?],
    COALESCE(CAST(c1.is_identity AS char(1)), ''-'') + '' / '' + COALESCE(CAST(c2.is_identity AS char(1)), ''-'') AS [Identity?],
    COALESCE(CAST(c1.is_computed AS char(1)), ''-'') + '' / '' + COALESCE(CAST(c2.is_computed AS char(1)), ''-'') AS [Computed?]    
FROM [$db1$].sys.columns c1
FULL OUTER JOIN [$db2$].sys.columns c2 ON
    c2.name = c1.name
INNER JOIN [$db1$].sys.types t1 ON
    t1.system_type_id = c1.system_type_id AND
    t1.user_type_id = c1.user_type_id
INNER JOIN [$db1$].sys.types t2 ON
    t2.system_type_id = c2.system_type_id AND
    t2.user_type_id = c2.user_type_id
WHERE
    c1.object_id = (SELECT object_id FROM [$db1$].sys.objects o1 WHERE o1.name = ''$table1$'' AND o1.schema_id = (
                   (SELECT schema_id FROM [$db1$].sys.schemas s1 WHERE s1.name = ''$schema1$''))) AND
    c2.object_id = (SELECT object_id FROM [$db2$].sys.objects o2 WHERE o2.name = ''$table2$'' AND o2.schema_id = (
                   (SELECT schema_id FROM [$db2$].sys.schemas s2 WHERE s2.name = ''$schema2$'')))
) AS derived
ORDER BY
    ColumnName
'

SET @sql = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@sql,
    '$db1$', @db1),
    '$schema1$', @schema1),
    '$table1$', @table1),
    '$db2$', @db2),
    '$schema2$', @schema2),
    '$table2$', @table2)
 
--PRINT @sql

EXEC (@sql)
0
 

Author Comment

by:JGH5
Comment Utility
Thank you Scott; I tested the script and it provides only the differences.  How could this be modified to include the differences plus the rest of the columns in the tables?
0
 
LVL 69

Expert Comment

by:ScottPletcher
Comment Utility
Hmm, it should list ALL columns from BOTH tables.

Hmm, wait, to be safe, change the INNER JOINs to LEFT OUTER JOINs.  Sorry about that :-) .

It just has columns that tell you if there were differences or not.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now