2

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

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 函数中做哪些更改?

4

2 回答 2

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;
于 2013-07-15T11:51:10.227 回答
0
DECLARE @user_ids NVARCHAR(MAX) = N'203616, 198667, 193718, 188769, 183820, 178871, 173922, 168973, 164024, 159075, 154126, 149177, 144228, 139279, 134330, 129381, 124432, 119483, 114534, 109585, 104636, 99687, 94738, 89789, 84840, 79891, 74942, 69993, 65044, 60095, 55146'
 
DECLARE @sql_xml XML = Cast('<root><U>'+ Replace(@user_ids, ',', '</U><U>')+ '</U></root>' AS XML)
    
SELECT f.x.value('.', 'BIGINT') AS user_id
INTO #users
FROM @sql_xml.nodes('/root/U') f(x)
    
SELECT * 
FROM #users

表格图像

于 2021-09-09T14:31:18.020 回答