如何使用fuction或SP从SQL中的字符串中删除非重复字符?

时间:2017-03-20 06:20:44

标签: sql stored-procedures sql-function

我有2列

第1个字符串如:'7,8,9,0,3'
第二个字符串如:'7,8,5,6,1'

我想要这样的输出:9,0,35,6,1或两者合并为9,0,3,5,6,1

2 个答案:

答案 0 :(得分:0)

将以下代码转换为SP:

DECLARE @Col1 VARCHAR(100)=    '7,8,9,0,3', @Col2 VARCHAR(100)=    '7,8,5,6,1'


DECLARE @Table1 Table (Col1 VARCHAR(100))

DECLARE @Table2 Table (Col2 VARCHAR(100))

INSERT INTO @Table1 VALUES ( @Col1)

INSERT INTO @Table2 VALUES (@Col2)



;with tmp( Data,Col1) as (

select CONVERT(VARCHAR(100),LEFT(Col1, CHARINDEX(',',Col1+',')-1)),
    STUFF(Col1, 1, CHARINDEX(',',Col1+','), '')
FROM @Table1
union all
select CONVERT(VARCHAR(100),LEFT(Col1, CHARINDEX(',',Col1+',')-1)),
    STUFF(Col1, 1, CHARINDEX(',',Col1+','), '')
FROM tmp
WHERE Col1>''
)
select ID = IDENTITY(INT,1,1),CONVERT(VARCHAR(100),Data) AS Col1
INTO #T1
from tmp

;with tmp( Data,Col2) as (
select CONVERT(VARCHAR(100),LEFT(Col2, CHARINDEX(',',Col2+',')-1)),
    STUFF(Col2, 1, CHARINDEX(',',Col2+','), '')
FROM @Table2
union all
select CONVERT(VARCHAR(100),LEFT(Col2, CHARINDEX(',',Col2+',')-1)),
    STUFF(Col2, 1, CHARINDEX(',',Col2+','), '')
FROM tmp
WHERE Col2>''
)
select ID = IDENTITY(INT,1,1),CONVERT(VARCHAR(100),Data) AS Col2
INTO #T2
from tmp

SELECT ID = IDENTITY(INT,1,1),Col1
INTO #T3
FROM
(
    SELECT Col1
    FROM #T1
    EXCEPT
    SELECT *
    FROM
    (
        SELECT Col1
        FROM #T1
        INTERSECT
        SELECT Col2
        FROM #T2
    )T3

    UNION ALL

    SELECT Col2
    FROM #T2
    EXCEPT
    SELECT *
    FROM
    (
        SELECT Col1
        FROM #T1
        INTERSECT
        SELECT Col2
        FROM #T2
    )T4
)T5

SELECT DISTINCT STUFF((SELECT ',' + Col1
                           FROM #T3 T1
                           --WHERE T1.ID=T2.Id
                           FOR XML PATH ('')),1,1,'')
FROM #T3 T2

DROP TABLE #T1,#T2,#T3

Demo

答案 1 :(得分:-1)

您需要做的是在2列之间的同一个表上进行完全外连接。

SELECT distinct A.name1,B.name2
FROM <TABLE> A full outer join <TABLE> B  on A.name1 = B.name2
where A.name1 is null or B.name2 is null