【问题标题】:Looking for occurrence of substrings in another string寻找另一个字符串中出现的子字符串
【发布时间】:2016-07-27 13:14:14
【问题描述】:

我有两个 MS SQL 表:

如果表一的字符串的所有字符都包含在表二的字符串中,我必须用循环说。

例如

 (_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_)

希望你能帮忙!

谢谢

--编辑

下划线是分隔符

结果如下所示:

enter image description here

【问题讨论】:

  • both 表中的行样本数据将有助于解释您要执行的操作。不清楚你想要什么结果。
  • 下划线是分隔符还是输入的一部分?
  • 使用校验和来比较table1和table2!!
  • 校验和不起作用 SELECT CHECKSUM ('_a_b_c'), CHECKSUM('_b_c_a') 产生不同的输出,但 OP 希望这是真的
  • 您的数据格式似乎有误。如果您将列表存储在字符串中,那么您应该修复基础数据以使用联结表。

标签: sql sql-server substring


【解决方案1】:

你可以试试这个:

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

结果:

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

(5 row(s) affected)

我可以看到_a_b_ 包含在_a_c_b_d_ 中。

【讨论】:

    猜你喜欢
    • 2022-06-17
    • 1970-01-01
    • 2013-07-10
    • 2020-04-28
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 2014-11-10
    • 2023-03-15
    相关资源
    最近更新 更多