Not sure what the output you are looking for is. Also, with both tables having Pat#ID and Accession#, but the Pat#ID in one table matching with the Accession# in the second table somehow seems not quite right. Then again, I don't know your business logic, so that indeed may be what you want. Anyhow, here is an example data set and a query. See if this will help you figure out what you might need to do:CREATE TABLE #tmpAdhoc(CPT INT, PatId VARCHAR(32), Accession VARCHAR(32));CREATE TABLE #tmpPathwayAccessions (PatId VARCHAR(32), Accession VARCHAR(32));INSERT INTO #tmpAdhoc VALUES(82106,'SC11-000163-TX','AP11-003849-DH'),(82106,'SC11-000163-TX','AP11-003850-AD'),(82106,'SC11-000163-TX','AP11-003850-DH'),(82106,'SC11-000163-TX','AP11-003851-AD'),(82106,'SC11-000163-TX','AP11-003851-DH');INSERT INTO #tmpPathwayAccessions VALUES( '003850','abcd'), ('004444','efgh');SELECT t1.[CPT], t1.PatId, t2.AccessionFROM #tmpAdhoc T1 LEFT JOIN #tmpPathwayAccessions T2 ON t1.Accession LIKE '%' + t2.PatId + '%'WHERE t1.[Accession] IS NOT NULLDROP TABLE #tmpAdhoc;DROP TABLE #tmpPathwayAccessions;
Edit: One thing I hadn't noticed in your original query may be the cause of the problem. See the part I have marked in red above.