T-SQL, Remove space in string

2020-06-22 09:23发布

问题:

I have two strings in SQL and the REPLACE function only works on one of them, why is that?

Example 1:

SELECT REPLACE('18 286.74', ' ', '')

Example 2:

SELECT REPLACE('z z', ' ', '')

Example 1's output is still "18 286.74" whereas Example 2's output is "zz". Why does SQL not react the same way to both strings?

UPDATE:

When running select replace('123 123.12', ' ', '') that works fine, still not with '18 286.74'.

回答1:

Test it the following way.

select unicode(substring('18 286.74', 3, 1))

If the code returns 32 then it's a space, if not, it's a different Unicode character and your replace ' ' won't work.



回答2:

maybe cast is needed.

UPD: or not(on sql 2005 works fine too)



回答3:

Are you sure it is a space? i.e. the same whitespace character that you are passing as the second argument? The code you've posted works fine for me on SQL Server 2008.

Re working on your friends PC - perhaps the whitespace got normalized when you sent it to him?



回答4:

You are probably using non-breakable space.

I could reproduce it by typing ALT+0160 into the number in SELECT REPLACE('18 286.74', ' ', '')

Could you please issue this following:

SELECT CAST('18 286.74' AS BINARY), REPLACE('18 286.74', ' ', '')

by copying the '18 286.74' from REPLACE into CAST?



回答5:

I was having the same issue and found that it was a char(10) (line feed). when copied out of Managment Studio it became a char(32) but in the record it was a char(10) try

Select Replace(@string, char(13), '')


标签: tsql replace