Database Journal
MS SQL Oracle DB2 Access MySQL PostgreSQL Sybase PHP SQL Etc SQL Scripts & Samples Links Database Forum

» Database Journal Home
» Database Articles
» Database Tutorials
MS SQL
Oracle
DB2
MS Access
MySQL
» RESOURCES
Database Tools
SQL Scripts & Samples
Links
» Database Forum
» Sitemap
Free Newsletters:
DatabaseDaily  
News Via RSS Feed


follow us on Twitter
Database Journal |DBA Support |SQLCourse |SQLCourse2
 

Featured Database Articles

SQL Scripts & Samples

Posted Aug 7, 2002

SQL Script for Comparing the Contents of Two Tables

By DatabaseJournal.com Staff


Here's some SQL code from Eli Leiba that will all you to compare two tables -- say, table A and table B -- to determine if their content is the same. Assuming that A and B have the same structure, here's how it works:

First, from set theory, recall that: If ((|A| = |B|) && |A U B| = |A|)) ====>>> A = B

|A| = NUMBER of rows in A
|B| = NUMBER of rows in B

Here's the SQL code (with T-SQL syntax, but can be adapted for other DBMS's):


declare @cnt1 int 
declare @cnt2 int 
declare @cnt3 int 
declare @res bit 

select @cnt1 = count(*) from A 
select @cnt2 = count(*) from B 
select @cnt3 = count('x') 
     from (select * from A 
     UNION 
     select * from B) as t 

if (@cnt1 = @cnt2) and (@cnt2 = @cnt3) 
 begin 
   set @res = 1 
   print 'A = B' 
 end 
 else 
  begin 
    set @res = 0 
    print 'A <> B' 
  end 
go 


» See All Articles by Columnist Eli Leiba




SQL Scripts & Samples Archives

Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 




Latest Forum Threads
SQL Scripts & Samples Forum
Topic By Replies Updated
sql help!! add 1 August 22nd, 11:58 AM
How To Combine These 2 Queries into 1 Query ? tarek_land 1 June 7th, 08:37 AM
solving query svibuk 1 February 3rd, 06:08 AM
converting from a character string to uniqueidentifier saturnius 4 January 4th, 05:56 AM


















Thanks for your registration, follow us on our social networks to keep up-to-date