SQL Server查询替换额外的“;;;”人物

时间:2014-01-24 08:50:32

标签: sql sql-server

我的表中有以下行,我想删除重复的分号(;)。

ColumnName
Test;Test2;;;Test3;;;;Test4;
Test;;;Test2;Test3;;Test4;
Test;;;;;;;;;;;;;;;;;Test2;;;;Test3;;;;;Test4;

从上面的行,我想删除重复的分号(;)并只保留一个分号(;)

如下所示

ColumnName
Test;Test2;Test3;Test4
Test;Test2;Test3;Test4
Test;Test2;Test3;Test4

由于 拉杰什

3 个答案:

答案 0 :(得分:9)

我喜欢使用这种模式。 AFAIK,最初由Jeff Moden在SQLServerCentral(link)上发布。 我已将所有行中的终端分号留下,因为它们是单个出现项。要删除SUBSTRING()LEFT()

CREATE TABLE #MyTable (MyColumn VARCHAR(500))
INSERT INTO #MyTable
SELECT 'Test;Test2;;;Test3;;;;Test4;'   UNION ALL
SELECT 'Test;;;Test2;Test3;;Test4;'     UNION ALL
SELECT 'Test;;;;;;;;;;;;;;;;;Test2;;;;Test3;;;;;Test4;' 

-- Where '^|' nor its revers '|^' is a sequence of characters that does not occur in the table\field
SELECT REPLACE(REPLACE(REPLACE(MyColumn, ';', '^|'), '|^', ''), '^|', ';')
FROM #MyTable   

-- If you MUST remove terminal semi-colon
SELECT CleanText2   = LEFT(CleanText1, LEN(CleanText1)-1)
FROM
(
    SELECT CleanText1   = REPLACE(REPLACE(REPLACE(MyColumn, ';', '^|'), '|^', ''), '^|', ';')
    FROM #MyTable
)DT

答案 1 :(得分:1)

DECLARE @TestTable TABLE(Column1  NVARCHAR(MAX)) 

INSERT INTO @TestTable VALUES 
('Test;Test2;;;Test3;;;;Test4;'),
('Test;;;Test2;Test3;;Test4;'),
('Test;;;;;;;;;;;;;;;;;Test2;;;;Test3;;;;;Test4;')

SELECT        replace(
                  replace(
                     replace(
                        LTrim(RTrim(Column1)), 
                     ';;',';|'),                    
                  '|;',''),                         
               '|','') AS Fixed
 FROM @TestTable

结果集

╔═════════════════════════╗
║          Fixed          ║
╠═════════════════════════╣
║ Test;Test2;Test3;Test4; ║
║ Test;Test2;Test3;Test4; ║
║ Test;Test2;Test3;Test4; ║
╚═════════════════════════╝

答案 2 :(得分:1)

SELECT replace(replace(replace(Column1,';','<>'),'><',''),'<>',';') from table

试试这个

它的afaik我刚刚取代所有;通过&lt;&gt;然后到;