如何从sql server中的逗号分隔字符串中删除重复值。不使用功能
Declare @data varchar(max) = '34.22,768.55,34.22,123.34,12,999.0,999.0'
我的预期结果应为
34.22,768.55,123.34,12,999.0
我尝试过这个查询,但它不会从变量中删除重复项。
Declare @data varchar(max) = '34.22,768.55,34.22,123.34,12,999.0,999.0'
set @data= (select '' + cast(cast('<d>'+replace(@data, ', ',',</d><d>')+'</d>' as xml).query('distinct-values(/d)') as varchar(max)) +'')
答案 0 :(得分:2)
试试这个
UniqNumber
---------------------------
12,123.34,34.22,768.55,999.0
<强>结果强>
CREATE TABLE table1
(
someNumber TYPE1
CHECK (someNumber.TYPE1 BETWEEN 11111111 AND 9999999999999)
);
答案 1 :(得分:2)
请尝试此操作 -
DECLARE @x AS XML=''
Declare @finalstring varchar(max) = ''
DECLARE @Param AS VARCHAR(100) = '34.22,768.55,34.22,123.34,12,999.0,999.0'
SET @x = CAST('<A>'+ REPLACE(@Param,',','</A><A>')+ '</A>' AS XML)
select @finalstring = @finalstring + value + ',' from (
SELECT t.value('.', 'VARCHAR(10)') Value FROM @x.nodes('/A') AS x(t))p
GROUP BY value
PRINT SUBSTRING(@finalstring,0,LEN(@finalstring))
<强>输出强>
12,123.34,34.22,768.55,999.0
适用于sql 2016 +
Declare @data varchar(max) = '34.22,768.55,34.22,123.34,12,999.0,999.0'
Declare @finalstring varchar(max) = ''
select @finalstring = @finalstring + value + ',' from string_split(@data,',')
GROUP BY value
PRINT SUBSTRING(@finalstring,0,LEN(@finalstring))
<强>输出强>
12,123.34,34.22,768.55,999.0
答案 2 :(得分:1)
试试这个
Declare @data varchar(max) = '34.22,768.55,34.22,123.34,12,999.0,999.0'
;WITH CTE
AS
(
SELECT
MyStr = SUBSTRING(@data,CHARINDEX(',',@Data)+1,LEN(@data)),
Val = SUBSTRING(@data,1,CHARINDEX(',',@data)-1)
UNION ALL
SELECT
MyStr = CASE WHEN CHARINDEX(',',MyStr)>0
THEN SUBSTRING(MyStr,CHARINDEX(',',MyStr)+1,LEN(MyStr))
ELSE NULL END,
Val = CASE WHEN CHARINDEX(',',MyStr)>0
THEN SUBSTRING(MyStr,1,CHARINDEX(',',MyStr)-1)
ELSE MyStr END
FROM CTE
WHERE ISNULL(REPLACE(MyStr,',',''),'')<>''
)
SELECT
Val = SUBSTRING(List,1,LEN(List)-1)
FROM
(
SELECT
DISTINCT Val+','
FROM CTE
WHERE ISNULL(MyStr ,'')<>''
FOR XML PATH('')
)Q(List)
我的结果
12,123.34,34.22,768.55,999.0
答案 3 :(得分:1)
这是另一种简单的方法。
Declare @data Nvarchar(max) = N'34.22,768.55,34.22,123.34,12,999.0,999.0'
, @data2 Nvarchar(max)='';
SELECT @data = N'SELECT @DATA_DIST= @DATA_DIST+VAL+'',''
FROM (SELECT '''+replace(@data,',',''' AS VAL UNION SELECT ''')+''')A';
EXECUTE sp_executesql @data,N'@DATA_DIST varchar(MAX) OUTPUT',@DATA_DIST=@data2 OUTPUT;
SELECT LEFT(@data2,LEN(@data2)-1);
<强>结果:强>
12,123.34,34.22,768.55,999.0