比较sql中的逗号分隔值

时间:2013-07-15 11:26:16

标签: sql sql-server sql-server-2008 csv

我正在尝试编写一个函数来比较SQL中的逗号分隔值 我从互联网上获取了一些代码:

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

然后我做了一个功能:

CREATE FUNCTION [dbo].[fnCompareCSVString] 
(   
    @str1 nvarchar(50),
    @str2 nvarchar(50)
)

RETURNS  int
AS
BEGIN
    SELECT CASE WHEN EXISTS 
    (
       SELECT 1 FROM dbo.Split(@str1)
       WHERE ', ' + LTRIM(@str2) + ',' 
         LIKE '%, ' + LTRIM(Item) + ',%'
    ) THEN 1 ELSE 0 END;
END

我不擅长SQL我知道这是错误的

问题:

我想编写一个函数来比较逗号分隔值,这些值在比较后将采用两个值(逗号分隔值),返回值将为true或false

我在这个SQL函数中需要做哪些更改?

1 个答案:

答案 0 :(得分:1)

这是你在找什么?

真/假结果

-- matches only those values which exist in both CSV sets
SELECT T1.[Item], CASE  WHEN T2.[Item] IS NULL THEN 0 ELSE 1 END AS [Match] 
FROM [dbo].[Split]('val1,val2,val3', ',') AS T1
    LEFT JOIN [dbo].[Split]('val3,val4', ',') AS T2 on T1.[Item] = T2.[Item]

返回

Item    Match
val1    0
val2    0
val3    1

仅匹配

-- matches only those values which exist in both CSV sets
SELECT T1.[Item] 
FROM [dbo].[Split]('val1,val2,val3', ',') AS T1
    INNER JOIN [dbo].[Split]('val3,val4', ',') AS T2 on T1.[Item] = T2.[Item]

返回

Item
val3

拆分功能

CREATE FUNCTION [dbo].[Split] 
(   
    @s VARCHAR(max),
    @split CHAR(1)
)
RETURNS @temptable TABLE ([Item] VARCHAR(MAX))    
AS
BEGIN
    DECLARE @x XML

    SELECT @x = CONVERT(xml,'<root><s>' + REPLACE(@s,@split,'</s><s>') + '</s></root>');

    INSERT INTO @temptable          
    SELECT [Value] = T.c.value('.','varchar(20)')
    FROM @X.nodes('/root/s') T(c);
RETURN
END;