[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 779
  • Last Modified:

T-SQL query, comparing data in two tables

I am comparing data in two identical tables, Ideally the data should be the same but there are some differences. I found those rows which are different using EXCEPT (there are multiple ways to do this).
If the row has not matching data then: some of this row columns have the same data and some have not the same data.
I'd like to write sql code that for every not matching row returns a list of not matching columns.

2 Solutions
Brian CroweCommented:
Could you give an example of the input and output you are looking for?
If the two fields are identical between the two different tables then I'm using 1, otherwise, 0.  This example compares 3 fields (fld1, fld2, fld3):
SELECT	pk	=	ISNULL(a.pk,b.pk)
,	fld1	=	CASE WHEN a.fld1 = b.fld1 THEN 1 else 0 END
,	fld2	=	CASE WHEN a.fld2 = b.fld2 THEN 1 else 0 END
,	fld3	=	CASE WHEN a.fld3 = b.fld3 THEN 1 else 0 END
FROM	tableA	a
JOIN	tableB	b	ON	a.pk = b.pk

Open in new window


Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now