我必须包含逗号分隔字符串的变量:
@v1 = 'hello, world, one, two'
@v2 = 'jump, down, yes, one'
如果至少有一个匹配项,我需要一个返回 TRUE 的函数。所以在上面的例子中,它会返回 TRUE,因为值 'one' 在两个字符串中。
这在 SQL 中可能吗?
我必须包含逗号分隔字符串的变量:
@v1 = 'hello, world, one, two'
@v2 = 'jump, down, yes, one'
如果至少有一个匹配项,我需要一个返回 TRUE 的函数。所以在上面的例子中,它会返回 TRUE,因为值 'one' 在两个字符串中。
这在 SQL 中可能吗?
Use a split function (many examples here - CLR is going to be your best option in most cases back before SQL Server 2016 - now you should use STRING_SPLIT()
).
Once you have a split function, the rest is quite easy. The model would be something like this:
DECLARE @v1 VARCHAR(MAX) = 'hello, world, one, two',
@v2 VARCHAR(MAX) = 'jump, down, yes, one';
SELECT CASE WHEN EXISTS
(
SELECT 1
FROM dbo.Split(@v1) AS a
INNER JOIN dbo.Split(@v2) AS b
ON a.Item = b.Item
)
THEN 1 ELSE 0 END;
You can even reduce this to only call the function once:
SELECT CASE WHEN EXISTS
(
SELECT 1 FROM dbo.Split(@v1)
WHERE ', ' + LTRIM(@v2) + ','
LIKE '%, ' + LTRIM(Item) + ',%'
) THEN 1 ELSE 0 END;
On 2016+:
SELECT CASE WHEN EXISTS
(
SELECT 1 FROM STRING_SPLIT(@v1, ',')
WHERE ', ' + LTRIM(@v2) + ','
LIKE '%, ' + LTRIM([Value]) + ',%'
) THEN 1 ELSE 0 END;
您可以使用 CTE 将字符串拆分为 xml 节点,然后将单词插入表变量中。加入表变量将显示任何匹配项
DECLARE @v1 VARCHAR(200) = 'hello, world, one, two'
DECLARE @v2 VARCHAR(200) = 'jump, down, yes, one'
DECLARE @v1Words TABLE (word VARCHAR(100))
DECLARE @v2Words TABLE (word VARCHAR(100))
;WITH cteSplitV1 AS(
SELECT CAST('<word>' + REPLACE(@v1,', ','</word><word>') + '</word>' AS XML) AS words)
INSERT INTO @v1Words(word)
SELECT word.x.value('.','VARCHAR(100)') AS [word]
FROM cteSplitV1
CROSS APPLY words.nodes('/word') AS word(x)
;WITH cteSplitV2 AS(
SELECT CAST('<word>' + REPLACE(@v2,', ','</word><word>') + '</word>' AS XML) AS words)
INSERT INTO @v2Words(word)
SELECT word.x.value('.','VARCHAR(100)') AS [word]
FROM cteSplitV2
CROSS APPLY words.nodes('/word') AS word(x)
SELECT *
FROM @v1Words v1
JOIN @v2Words v2
ON v1.word = v2.word