2017-03-11 97 views
0

我在我的SQL表中獲得了一列,其中一些值是分開的bij "。 這個字符串中的一些值是重複的,我想刪除。這是我的數據的一個例子:首先,我要拆分的字符串,然後刪除重複如何從SQL中的字符串中刪除重複記錄

--------------- 
| qw"er  | 
--------------- 
| q"w"  | 
--------------- 
| f"k"s"g  | 
--------------- 

--------------- 
| qw"qw"er"er | 
--------------- 
| q"w"w"q  | 
--------------- 
| f"k"s"g  | 
--------------- 

現在的結果應該更換任何重複。有誰能幫我解決這個問題嗎?

+0

多個值永遠不會存儲在一列! –

+1

@juergend這不是我在做什麼,我從另一個程序中獲取這個數據,它像這樣存儲它 –

+0

在SQL Server中它可以使用STRING_SPLIT和CROSS APPLY來實現。首先顯示整個表格。 –

回答

2

選項1帶有一個Parse功能

Declare @YourTable table (ID int,YourCol varchar(50)) 
Insert Into @YourTable values 
(1,'qw"qw"er"er'), 
(2,'q"w"w"q'), 
(3,'f"k"s"g') 

Select A.ID 
     ,A.YourCol 
     ,DeDuped = Stuff((Select '"' + RetVal 
          From (Select RetSeq=Min(RetSeq),RetVal 
            From [dbo].[udf-Str-Parse](A.YourCol,'"') 
            Group By RetVal) P 
          Order by 1 For XML Path('')),1,1,'') 
From @YourTable A 

返回

ID YourCol  DeDuped 
1 qw"qw"er"er qw"er 
2 q"w"w"q  q"w 
3 f"k"s"g  f"k"s"g 

選項2:如果沒有一個解析函數

Declare @YourTable table (ID int,YourCol varchar(50)) 
Insert Into @YourTable values 
(1,'qw"qw"er"er'), 
(2,'q"w"w"q'), 
(3,'f"k"s"g') 

Select A.ID 
     ,A.YourCol 
     ,DeDuped = Stuff((Select '"' + RetVal 
          From (Select RetSeq=Min(RetSeq),RetVal 
            From (
              Select RetSeq = Row_Number() over (Order By (Select null)) 
                ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)'))) 
              From (Select x = Cast('<x>' + replace((Select replace(A.YourCol,'"','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A 
              Cross Apply x.nodes('x') AS B(i) 
             ) P1 
            Group By RetVal) P 
          Order by RetSeq 
          For XML Path('')),1,1,'') 
From @YourTable A 

返回

ID YourCol  DeDuped 
1 qw"qw"er"er qw"er 
2 q"w"w"q  q"w 
3 f"k"s"g  f"k"s"g 

的UDF如果有興趣

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10)) 
Returns Table 
As 
Return ( 
    Select RetSeq = Row_Number() over (Order By (Select null)) 
      ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)'))) 
    From (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A 
    Cross Apply x.nodes('x') AS B(i) 
); 
--Thanks Shnugo for making this XML safe 
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',') 
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ') 
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',') 
--Performance On a 5,000 random sample -8K 77.8ms, -1M 79ms (+1.16), -- 91.66ms (+13.8)