I'm having difficulty with a T-SQL query that joins 2 tables using a character column. I suspect that there are some whitespace differences causing the problem but have not been able to track them down. In order to test this theory I'd like to strip all of the whitespaces from the joining columns and see if that resolves the issue. Unfortunately, I'm stuck on how to remove all whitespaces in a T-SQL string. Here is a simple example showing what I've tried (see the test columns):
select
str,
test1 = replace(str, '\\s+' , ''),
test2 = replace(str, '[\s]*' , '')
from
(
values
(''),
(' '),
(' xyz'),
('abc '),
('hello world')
) d (str);
Is there a way to get this to work in T-SQL?
Clarification: by white space, I mean to strip out ALL of the following:
\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
This piece of code helped figure out exactly what kind of whitespace was present in the original query that had the join issue:
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;
It turned out there were carriage returns and new line feeds in the data of one of the tables. So using @scsimon's solution this problem was resolved by changing the join to this:
on REPLACE(REPLACE(a.fieldname, CHAR(10), ''), CHAR(13), '') = b.fieldname
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With