我需要删除字符串中特定字符两侧的空格

I need to remove spaces present either side of a particular character in a string

我有一个非常大的字符串值,其中包含由 '|' 分隔的数据。

例如

Declare @string NVARCHAR(MAX)

Set @String = 'My Name|Address 1|Address 2|......'

在一些字符串值中,我有类似的东西

@String = My Name|Address 1 | Address 2|.......

我需要删除 '|' 两边的 Space。如果只有一个Space,我用

Set @string = Replace(@string,' |','|')    
Set @string = Replace(@string,'| ','|')

如果我有多个 space 并且计数不能具体如

怎么办
@String = My Name|Address 1   | Address 2|.......

将两者结合使用 replace 将解决您的问题。试试这个

Declare @string varchar(500)

set @String = 'My Name|Address 1 | Address 2| Address 3 |.......'

select  Replace(Replace(@string,' |','|'),'| ','|')

这是一种解决方案:

declare @s varchar(8000);
set @s = 'test                  |    test|test'

declare @tmp varchar(8000);
declare @x int;
set @x = 4096

while @x > 0
    begin
        set @tmp = replace(replace(@s, replicate(' ', @x) + '|', '|'), '|' + replicate(' ', @x), '|')
        if (@tmp = @s) set @x = @x / 2
        set @s = @tmp
    end

print @s

想法是替换空格,直到替换不再更改字符串。您可以简单地继续替换“|”和'| ' 和 '|',但上面的代码试图更聪明一点并替换更大的块(从 4096 个空格开始,每一步除以 2)。

此查询可能对您有所帮助。

Declare @string

Set @String = 'My Name|Address 1  |  Address 2 |......'

--Query to remove spaces before and after a specific character

SET @String=(SELECT replace(replace(replace(@String, '|','|'),' ',''),'/t',' '))

我已经在查询中编写了逻辑

DECLARE @String NVARCHAR(MAX) = 'My Name|Address 1        |Address 2  |'
        -- Since '|' inside the STUFF removes the first word, we append that word
SELECT  LEFT(LTRIM(@String),1) + STUFF((SELECT '|' + CAST(Ids AS VARCHAR(500)) [text()]
         FROM 
        (
            -- Converts each value to rows and remove the spaces on start and end
            SELECT LTRIM(RTRIM(PARSENAME(REPLACE(Split.a.value('.', 'VARCHAR(500)'),'-','.'),1))) 'Ids' 
            FROM  
            (
                 SELECT CAST ('<M>' + REPLACE(@String, '|', '</M><M>') + '</M>' AS XML) AS Data       
            ) AS A 
            CROSS APPLY Data.nodes ('/M') AS Split(a)
        )TAB
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,'') + '|' COLS