Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
SQL Select to compare two tables
Message
 
General information
Forum:
Visual FoxPro
Category:
Databases,Tables, Views, Indexing and SQL syntax
Miscellaneous
Thread ID:
01683376
Message ID:
01683460
Views:
43
>Hi,
>
>Say, I have two tables in the SQL Server DB. The structure of the tables is the same. And most of the records are the same (my assumption). I want to create a SQL Select that would show me just those rows that exist in one table but do not exist in another table.
>How would you create such a SQL Select?
>
>TIA

To get rows that have same PK but some columns are different you would write something like this
select T1.Id, T1.Column1 as T1Column1, T2.Column2 as T2Column1, etc.
from Table1 T1 inner join Table2 T2 on T1.ID = T2.Id
where T1.Column1<>T2.Column2 or T1.Column2<>T2.Column2 etc
This is assuming that all columns are not nullable (if nullable you may use ISNULL(T1.Column1,'') not equal ISNULL(T2.Column1,'') for comparison.

The alternative would be to create a SHA value based on several column concatenated (again, assuming columns are not nullable) and compare that. This is what we use. We use some custom function to calculate SHA value, but you can also use HASBYTES() function. Check in the help https://docs.microsoft.com/en-us/sql/t-sql/functions/hashbytes-transact-sql?view=sql-server-ver15 (only for character columns, you can concatenate them together before calculating). If you need to check for difference often, you can have it either as computed column or save as a permanent column and update using a trigger when table gets updated or new values inserted.
If it's not broken, fix it until it is.


My Blog
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform