If I have a value something like '10,10,20,30,40,20' in a field of table, then I want to make it as '10,20,30,40'
Is there any sql function to do such thing?
Thanks Sudhakar
using Jeff's DelimitedSplit8K from http://www.sqlservercentral.com/articles/Tally+Table/72993/
declare @value varchar(100) = '10,10,20,30,40,20',
@new_value varchar(100)
select @new_value = isnull(@new_value + ',', '') + Item
from DelimitedSplit8K(@value, ',')
group by Item
order by Item
select @new_value
Did this long ago. This might need some modifications. But it generates output.
Try :
DECLARE @Data_String AS VARCHAR(1000), @Result as varchar(1000)=''
SET @Data_String = '10,10,20,30,40,20'
SET @Data_String = REPLACE(@Data_String,'|',',')
select @Data_String;
SELECT @Result=@Result+col+',' from(
SELECT DISTINCT t.c.value('.','varchar(100)') col from(
SELECT cast('<A>'+replace(@Data_String,',','</A><A>')+'</A>' as xml)col1)data
cross apply col1.nodes('/A') as t(c))Data
SELECT LEFT(@Result,LEN(@Result)-1)
believing it stores integer number you can get them with creating a function first you need to split the values then have to use a distinct function as below
1st create a function like
CREATE FUNCTION [dbo].[idpGetSplitedString]
(
@String varchar(8000),
@Delimiter char(1)
)
RETURNS
@temptable TABLE
(
items varchar(8000)
)
AS
BEGIN
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(rtrim(ltrim(@slice)))
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
RETURN
END
then call the function like
select [dbo].idpGetSplitedString as Values
DISTINCT. Yu also have more safety(correct data type) and much better performance.