我在使用字符列连接 2 个表的 T-SQL 查询时遇到了困难。我怀疑有一些空白差异导致了问题,但无法追踪它们。为了测试这个理论,我想从连接列中去除所有空格,看看是否能解决问题。不幸的是,我被困在如何删除 T-SQL 字符串中的所有空格上。这是一个简单的示例,显示了我尝试过的内容(请参阅测试列):
select
str,
test1 = replace(str, '\\s+' , ''),
test2 = replace(str, '[\s]*' , '')
from
(
values
(''),
(' '),
(' xyz'),
('abc '),
('hello world')
) d (str);
有没有办法让它在 T-SQL 中工作?
澄清:通过空格,我的意思是去除以下所有内容:
\s white space (space, \r, \n, \t, \v, \f)
' ' space
\t (horizontal) tab
\v vertical tab
\b backspace
\r carriage return
\n newline
\f form feed
\u00a0 non-breaking space
最佳答案
这段代码有助于准确找出存在连接问题的原始查询中存在哪种空格:
select distinct
fieldname,
space = iif(charindex(char(32), fieldname) > 0, 1, 0),
horizontal_tab = iif(charindex(char(9), fieldname) > 0, 1, 0),
vertical_tab = iif(charindex(char(11), fieldname) > 0, 1, 0),
backspace = iif(charindex(char(8), fieldname) > 0, 1, 0),
carriage_return = iif(charindex(char(13), fieldname) > 0, 1, 0),
newline = iif(charindex(char(10), fieldname) > 0, 1, 0),
formfeed = iif(charindex(char(12), fieldname) > 0, 1, 0),
nonbreakingspace = iif(charindex(char(255), fieldname) > 0, 1, 0)
from tablename;
结果发现其中一个表的数据中有回车和换行符。因此,使用@scsimon 的解决方案,通过将连接更改为以下内容来解决此问题:
on REPLACE(REPLACE(a.fieldname, CHAR(10), ''), CHAR(13), '') = b.fieldname
关于sql-server - 如何从字符串中删除所有空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47423166/