Skip to content
Advertisement

How to compare two row in same table and return the data in response using stored procedure

I have to compare between two rows using two Id’s in the same table, and I want to get the columns and their values that are not matching in the stored procedure and I need to return it in JSON format.

Output:

I don’t have expertise in it however I tried the below SQL code but I need this in a very nice way and that too in a stored procedure and it should be returned in JSON format, please help!

What I have tried, please check the link below with sample example and query.

SQL Fiddle

Advertisement

Answer

You need to unpivot all the columns, then join each row to every other.

You can either pivot everything manually using CROSS APPLY (VALUES

The use of WHERE EXISTS (SELECT a.Value1 INTERSECT SELECT a.Value2) means that nulls will get taken into account properly.


Or you can use SELECT t.* FOR JSON and unpivot using OPENJSON

db<>fiddle

SQL Fiddle of actual data

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement