2016-04-06 4 views
1

Ich habe zwei MS SQL-Tabellen:die Suche nach Auftreten von Substrings in einem anderen String

screenshot of plain text, for some reason

Ich habe mit einer Schleife sagen, wenn alle Zeichen der Saiten der Tabelle einer in der Kette der enthaltenen Tabelle zwei.

z.

(_a_b_c_d_) is contained in (_a_c_b_d_) 

(_a_b_) is contained in (_g_b_a_) 

(_a_f_d_) is not contained in (_a_c_b_d_) 

Hoffe, Sie können helfen!

Dank

--edit

Unterstrichen sind delimiters

Hier welches Ergebnis aussehen kann:

enter image description here

+2

Beispieldaten mit Zeilen aus * beiden * Tabellen würden erklären, was Sie zu tun versuchen. Es ist nicht klar, welche Ergebnisse Sie wollen. –

+0

Sind die Unterstriche Trennzeichen oder ein Teil der Eingabe? – Nikki9696

+0

Verwenden Sie die Prüfsumme, um Tabelle1 und Tabelle2 zu vergleichen !! – Hiten004

Antwort

0

Sie können dies versuchen:

DECLARE @xml1 xml, @xml2 xml 

SELECT @xml1= (
SELECT (CAST('<b id="'+cast(id as nvarchar(2)) + '"><a>' + REPLACE(string,'_','</a><a>') + '</a></b>' as xml)) 
from table1 
FOR XML PATH('') 
) 

SELECT @xml2= (
SELECT (CAST('<b id="'+cast(id as nvarchar(2)) + '"><a>' + REPLACE(string,'_','</a><a>') + '</a></b>' as xml)) 
from table2 
FOR XML PATH('') 
) 

;WITH res1 AS (
SELECT t.v.value('../@id','int') as id, 
     t.v.value('.','char(1)') as chars 
FROM @xml1.nodes('/b/a') as t(v) 
WHERE t.v.value('.','char(1)') !='' 
), res2 AS (
SELECT t.v.value('../@id','int') as id, 
     t.v.value('.','char(1)') as chars 
FROM @xml2.nodes('/b/a') as t(v) 
WHERE t.v.value('.','char(1)') !='' 
), cte1 AS (
SELECT distinct id, (SELECT '_' + r.chars FROM res1 r WHERE r.id = r1.id ORDER BY r.id, r.chars FOR XML PATH('')) + '_' as string 
FROM res1 r1 
), cte2 AS (
SELECT distinct id, (SELECT '_' + r.chars FROM res2 r WHERE r.id = r2.id ORDER BY r.id, r.chars FOR XML PATH('')) + '_' as string 
FROM res2 r2 
) 

SELECT t1.id as table1id, t2.id as table2id 
FROM cte1 t1 
INNER JOIN cte2 t2 ON t2.string LIKE '%'+t1.string+'%' --t1.string LIKE '%'+t2.string+'%' 
ORDER BY t1.id 

Ergebnisse:

table1id table2id 
----------- ----------- 
1   1 
2   1 
2   4 
4   1 
4   3 

(5 row(s) affected) 

Wie ich _a_b_ sehen kann, ist in _a_c_b_d_ conteined.