Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

sql - 从SQL Server中的字符串中删除所有空格(Remove all spaces from a string in SQL Server)

What is the best way to remove all spaces from a string in SQL Server 2008?

(在SQL Server 2008中从字符串中删除所有空格的最佳方法是什么?)

LTRIM(RTRIM(' ab ')) would remove all spaces at the right and left of the string, but I also need to remove the space in the middle.

(LTRIM(RTRIM(' ab '))将删除字符串右侧和左侧的所有空格,但我还需要删除中间的空格。)

  ask by Ananth translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simply replace it;

(只需更换它;)

SELECT REPLACE(fld_or_variable, ' ', '')

Edit: Just to clarify;

(编辑:只是为了澄清;)

its a global replace, there is no need to trim() or worry about multiple spaces for either char or varchar :

(它是一个全局替换,不需要trim()或担心charvarchar多个空格:)

create table #t (
    c char(8),
    v varchar(8))

insert #t (c, v) values 
    ('a a'    , 'a a'    ),
    ('a a  '  , 'a a  '  ),
    ('  a a'  , '  a a'  ),
    ('  a a  ', '  a a  ')

select
    '"' + c + '"' [IN], '"' + replace(c, ' ', '') + '"' [OUT]
from #t  
union all select
    '"' + v + '"', '"' + replace(v, ' ', '') + '"'
from #t 

Result

(结果)

IN             OUT
===================
"a a     "     "aa"
"a a     "     "aa"
"  a a   "     "aa"
"  a a   "     "aa"
"a a"          "aa"
"a a  "        "aa"
"  a a"        "aa"
"  a a  "      "aa"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...