I have a stored procedures that accepts a comma separated list, then makes copies of that list with quoted strings and brackets, then uses those in a dynamic sql statement to build a pivot table with flexible number of columns.
My problem is that sometimes my users submit a list with duplicates, and that makes the pivot query fail. So I want to somehow select distinct from my comma separated strings.
Here's how I manipulate the initial string:
Declare @data varchar(max) = '150593, 150593, 150603, 150578, 150604'
Declare @bracketed varchar(max) = ''
Declare @quoted varchar(max) = ''
select @bracketed = @bracketed + quotename(rtrim(ltrim(Value))) + ', ',
@quoted = @quoted + quotename(rtrim(ltrim(Value)), '''') + ', '
from [dbo].[fnSplitStringAsTable](@data, ',')
Select @bracketed = LEFT(@bracketed, len(@bracketed) - 1),
@quoted = LEFT(@quoted, len(@quoted) - 1)
I'm thinking I should be able to add DISTINCT somewhere in this query,
but I can't make it work. How can I select distinct from comma separated lists?