-1

I have two strings:

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

Want to concatenate two strings into one without duplicates.

Expected Output:

str3
-------------------------------------------------------------
[First Name],[Last Name],[Middle Name],[Pin Code],[Address]
MAK
  • 6,824
  • 25
  • 74
  • 131

1 Answers1

3

You can use STRING_SPLIT() function and 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, ',');

Or

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), ',');

to get it as one row

declare @result varchar(max) = '';

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

SELECT @result;

Demo

and since you are working on SQL Server 2008 you need to create your own function such this one here.

Ilyes
  • 14,640
  • 4
  • 29
  • 55