如何比较两个以逗号分隔的字符串,如果至少有1个匹配则返回TRUE

时间:2013-03-07 20:20:32

标签: sql-server csv

我必须使用包含逗号分隔字符串的变量:

@v1 = 'hello, world, one, two'
@v2 = 'jump, down, yes, one'

如果至少有一个匹配,我需要一个返回TRUE的函数。所以在上面的例子中,它将返回TRUE,因为值'one'在两个字符串中。

这在SQL中是否可行?

2 个答案:

答案 0 :(得分:10)

使用拆分功能(many examples here - 在大多数情况下,CLR将是您的最佳选择)。

一旦你有一个分割功能,剩下的就很容易了。模型将是这样的:

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;

你甚至可以减少它只调用一次函数:

SELECT CASE WHEN EXISTS 
(
  SELECT 1 FROM dbo.Split(@v1)
  WHERE ', ' + LTRIM(@v2) + ',' 
    LIKE '%, ' + LTRIM(Item) + ',%'
) THEN 1 ELSE 0 END;

答案 1 :(得分:1)

您可以使用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