I have the following 2 tables which are linked by LINENUM and by TAG which is part of the FILENAME.
TABLE a TABLE b
LINENUM TAG LINENUM FILENAME
------------------- --------------------------
1 TAG-01 1 FN-TAG-01_130918
1 TAG-02 1 FN-TAG-04_120918
1 TAG-03 1 FN-TAG-09_130918
2 TAG-04 2 FN-TAG-04_130918
3 TAG-05 3 FN-TAG-05_110918
In our process FILENAME is typed manually so typos occur. I'm working on a tool to detect these errors and want something like this to be returned:
LINENUM TAG FILENAME Check
-----------------------------------------------------------
1 TAG-01 FN-TAG-01_130918 NULL
1 TAG-02 NULL FN-TAG-04_120918, FN-TAG-09_130918
1 TAG-03 NULL FN-TAG-04_120918, FN-TAG-09_130918
2 TAG-04 FN-TAG-04_130918 NULL
3 TAG-05 FN-TAG-05_110918 NULL
This is what I was trying:
;with Match as (
Select a.LINENUM, a.TAG, b.FILENAME
From a
left outer Join b on a.LINENUM = b.LINENUM and b.FILENAME like '%'+a.TAG+'%'),
This gives the first 3 columns but the tricky part starts as I want to join only those records of Table b that haven't been linked by the first relationship. So I continue...
Orphans as (
Select LINENUM, FILENAME
From b
WHERE NOT EXISTS (SELECT FILENAME
FROM Match
WHERE Match.FILENAME = b.FILENAME))
and finally:
Select Match.*
From Match
left outer join Orphans on Match.LINENUM = Orphans.LINENUM and Match.FILENAME is NULL
At that point the Records for LINENUM 1 and the unmatched FILENAME double and everything gets more complicated, beside the fact that applying this to my real case the query is executing extremly slow. So I probably need a completely different approach.
Any suggestions?
OK, after having declared Orphans the final Select statement would be:
Select Match.*, a.Comment
From Match
left outer Join (Select LINENUM, stuff((select ', ' + FILENAME from Orphans for xml path('')),1,1,'') AS Comment
From Orphans
Group by LINENUM)a on a.LINENUM = Match.LINENUM and Match.FILENAME is NULL
This returns the desidered table, but with a very bad performance when applied to my actual tables.
Anybody has a smarter idea?