Compare combination of two columns with combination of other two in SQL
I have 2 tables, tbl_NameCode and tbl_Bkp, having column ids and a name.
I need to select records from tbl_NameCode that are not in tbl_bkp.
SELECT * FROM tbl_Bkp
WHERE ? */COMBINATION OF ID,Name NOT IN (SELECT COMBINATION OF ID,NAME FROM tbl_NameCode )*/
How do I compare a combination of two columns with a combination of the other two?
+3
source to share
5 answers
Use LEFT JOIN to fetch all records from the left table and add where condition with a null check of the second table to find unmatched records of the left table
Try the following:
SELECT NC.ID, NC.Name
FROM tbl_NameCode NC
LEFT OUTER JOIN tbl_bkp A ON NC.ID = A.ID AND NC.Name = A.Name
WHERE A.ID IS NULL;
+2
source to share
you can also try this:
declare @tbl_NameCode table (id int, name varchar(100))
declare @tbl_Bkp table (id int, name varchar(100))
insert into @tbl_NameCode select 1, 'ABC'
union select 2, 'XYZ'
union select 3, 'PQR'
insert into @tbl_Bkp select 1, 'ABC'
union select 2, 'XXX'
union select 3, 'PQR'
select a.* from @tbl_Bkp a
left join @tbl_NameCode b on convert(varchar, a.id) + a.name = convert(varchar, b.id) + b.name
where b.id is null
+1
source to share