UPDATE dbo.Test
SET Required_result =
ISNULL
(
(
SELECT
-- Reassemble parts with no matches
result = STRING_AGG(LTRIM(SS.[value]), ', ')
FROM dbo.Test AS T2
CROSS APPLY STRING_SPLIT
(
-- Remove commas before splitting
REPLACE(T2.Col2, ',', ''),
-- Split on spaces
SPACE(1)
) AS SS
WHERE
-- For the current outer ID
T2.ID = dbo.Test.ID
-- Current part has no match
AND 0 =
CHARINDEX
(
SPACE(1) + LTRIM(SS.[value]) + SPACE(1),
SPACE(1) + T2.Col1 + SPACE(1)
)
),
-- Empty string instead of NULL if everything matched
SPACE(0)
);
如果需要保证保留 Col2 字符串组件的顺序,请在(需要 Azure SQL 数据库或 SQL Server 2022)的可选enable_ordinal参数中传递值 1STRING_SPLIT并添加WITHIN GROUP (ORDER BY SS.ordinal)到STRING_AGG聚合中:
UPDATE dbo.Test
SET Required_result =
ISNULL
(
(
SELECT
-- Reassemble parts with no matches
result = STRING_AGG(LTRIM(SS.[value]), ', ')
WITHIN GROUP (ORDER BY SS.ordinal)
FROM dbo.Test AS T2
CROSS APPLY STRING_SPLIT
(
-- Remove commas before splitting
REPLACE(T2.Col2, ',', ''),
-- Split on spaces
SPACE(1),
-- Enable ordinal
1
) AS SS
WHERE
-- For the current outer ID
T2.ID = dbo.Test.ID
-- Current part has no match
AND 0 =
CHARINDEX
(
SPACE(1) + LTRIM(SS.[value]) + SPACE(1),
SPACE(1) + T2.Col1 + SPACE(1)
)
),
-- Empty string instead of NULL if everything matched
SPACE(0)
);
样本数据
解决方案
结果
数据库<>小提琴
如果需要保证保留 Col2 字符串组件的顺序,请在(需要 Azure SQL 数据库或 SQL Server 2022)的可选enable_ordinal参数中传递值 1
STRING_SPLIT
并添加WITHIN GROUP (ORDER BY SS.ordinal)
到STRING_AGG
聚合中: