将两个字符串连接成一个没有重复的字符串

Concatenate two strings into one without duplicates

我有两个字符串:

DECLARE @str1 varchar(max) = '[First Name],[Last Name],[Middle Name]'
DECLARE @str2 varchar(max) = '[First Name],[Pin Code],[Address],[Last Name]'

想要将两个字符串无重复地连接成一个。

预期输出:

str3
-------------------------------------------------------------
[First Name],[Last Name],[Middle Name],[Pin Code],[Address]

您可以使用 STRING_SPLIT() 函数和 DISTINCT as

DECLARE @str1 varchar(max) = '[First Name],[Last Name],[Middle Name]';
DECLARE @str2 varchar(max) = '[First Name],[Pin Code],[Address],[Last Name]';

SELECT DISTINCT *
FROM STRING_SPLIT(@Str1 +','+ @Str2, ',');

DECLARE @str1 varchar(max) = '[First Name],[Last Name],[Middle Name]';
DECLARE @str2 varchar(max) = '[First Name],[Pin Code],[Address],[Last Name]';

SELECT DISTINCT *
FROM STRING_SPLIT(CONCAT(@Str1, ',', @Str2), ',');

将其作为一行

declare @result varchar(max) = '';

SELECT @result =  @result + value
FROM STRING_SPLIT(CONCAT(@Str1, ',', @Str2), ',')
group by value;

SELECT @result;

Demo

并且由于您在 SQL Server 2008 上工作,您需要创建自己的函数,例如 this one here