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
Do you mean this? It removes a whitespace (as in created with a spacebar) character
Replace(str,' ', '')
I would suggest that you remove spaces and tabs (4 spaces):
SELECT REPLACE(REPLACE(str,' ', ''), char(9), '')
Replace(str,' ', '')
worked for me.
Check this out:
select
myString,
test1 = replace(myString, ' ' , ''),
test2 = replace(myString, ' ' , '')
from
(
values
(''),
(' '),
(' xyz'),
('abc '),
('hello world')
) d (myString);
Screenshot of output:
Related
I want to replace rightmost same characters from string.
e.g string is like in this format
"GGENXG00126""XLOXXXXX"
in sql but last consecutive X lenght is not fix.
I already Tried in SQL is
select REPLACE('"GGENXG00126""XLOXXXXX"', 'X', '')
but using this all 'X' is removed. I want to remove only rightmost same characters and output expected "GGENG00126""LO".
You can replace all x with spaces, RTRIM, then undo the replacements:
SELECT '"' + REPLACE(RTRIM(REPLACE(SUBSTRING(str, 2, LEN(str) - 2), 'X', ' ')), ' ', 'X') + '"'
FROM (VALUES
('"GGENXG00126""XLOXXXXX"')
) v(str)
-- "GGENXG00126""XLO"
An alternative idea using PATINDEX and REVERSE, to find the first character that isn't the final character in the string. (Assumes all strings are quoted):
SELECT REVERSE(STUFF(R.ReverseString,1,PATINDEX('%[^' + LEFT(R.ReverseString,1) + ']%',R.ReverseString)-1,'')) + '"'
FROM (VALUES('"GGENXG00126""XLOXXXXX"'))V(YourString)
CROSS APPLY (VALUES(STUFF(REVERSE(V.YourString),1,1,''))) R(ReverseString);
You can try this below option-
DECLARE #InputString VARCHAR(200) = 'GGENXG00126""XLOXXXXX'
SELECT
LEFT(
#InputString,
LEN(#InputString)+
1-
PATINDEX(
'%[^X]%',
REVERSE(#InputString)
)
)
Output is-
GGENXG00126""XLO
This question already has answers here:
What is the Null Character literal in TSQL?
(6 answers)
Closed 5 years ago.
I have a string of type VARCHAR(128) in MS SQL Server, which has this value: 'abc '.
However, these trailing "spaces" are not regular spaces (ASCII 32), they are of ASCII 0. I want to trim these trailing "spaces", but I could not get it to work.
I have tried the following approaches:
ltrim and rtrim
replace('abc ', CHAR(0), '')
substring('abc ', 0, charindex(CHAR(0), 'abc '))
But none of these seem to work as intended.
How can I remove these trailing ASCII 0 characters from the string?
I tried your code and there was no replacement so I check the ASCII code of your space and it was 32, not 0:
select replace('abc ', CHAR(32), '') + '*', ascii(right('abc ', 1))
Here I make for you your test data
and replace char(0) using old sql server collation:
declare #t table (c varchar(128) collate latin1_general_ci_as);
insert into #t values ('abc' + replicate(char(0),10));
select c, len(replace(c, char(0), '')) as len_not_replaced,
replace(c collate SQL_Latin1_General_CP1_CI_AS, char(0), '') + '*' as correct_replacement
from #t;
LTRIM and RTRIM only remove spaces, not any whitespace character. If you are certain they are char(0) simply use replace.
declare #Something varchar(20) = 'abc' + replicate(char(0), 5) + 'def'
select replace(#Something, char(0), '')
I tried almost everything to remove some unnecessary characters from sql string but it's not working:
declare #string as char(20)=' my '
select #string as OriginalString
select len(Replace((#string),CHAR(10),''))as StrLen1;
SELECT len(REPLACE(REPLACE(#string, CHAR(13), ' '), CHAR(10), '')) as StrLen2
Output Screen
Need a way to get this done.
Of the three types of whitespace you seem to mention, space, newline, and carriage return, your #string only has spaces. But you never actually remove space. If you want to remove all three of these types of whitespace, you can try the following:
SELECT
LEN(REPLACE(REPLACE(REPLACE(#string, CHAR(13), ''), CHAR(10), ''), ' ', '')) AS StrLen2
The output from the above query is 2, since after removing the whitespace we are left with the string 'my'.
Demo
declare #newline char(2)
set #newline= char(13)+char(10) -- CR + LF
update **Your Table Here**
-- ItemCode is column Name,Find and replace values CRLF = ''
Set ItemCode=REPLACE(ItemCode,#newline,'')
where RIGHT(ItemCode,2) = #newline -- Maybe no need
If you just want to get rid of spaces:
declare #string as char(20)=' my '
select LTRIM(RTRIM(#string))
If you're trying to trim all spaces try this :
Select RTRIM(LTRIM(#string))
DEMO
I have a table with list of users as below.
christopher.j.sansom
vinay.prabhakar
Guillaume.de.Miribel (Stage 2B); jean-marie.pierron (Stage 3B)
ian.notley; pavan.sethi
Ron.M.Barbeau
jason.angelos
jonathan.l.lange, ramesh.t.murti,
nicole.f.cohen
Can we get the records as below. Need to return comma separated records as new rows.
christopher.j.sansom
vinay.prabhakar
Guillaume.de.Miribel
jean-marie.pierron
ian.notle
pavan.sethi
Ron.M.Barbeau
jason.angelos
jonathan.l.lange
ramesh.t.murti
nicole.f.cohen
See Regex here: https://regex101.com/r/hD2mQ8/1
You can use this pattern:
/(^[\w.-]+)|(?<=; |, )[\w.-]+/ with global and multi-line modifiers to capture the text that you need, but I'm not sure how you would return each one to a new line without seeing your current code.
To do that you need a string splitter query/function.
This is an example, there are other way to do it.
With Normalize AS (
SELECT REPLACE(CONCAT(REPLACE(names, ',', ';'), ';'), ';;', ';') Names
FROM Table1
), Splitter AS (
Select names String
, WordCounter = 0
, NWordStart = 1
, NWordEnd = CHARINDEX(';', names)
, Word = CAST('' as nvarchar(255))
, WordNumber = LEN(names) - LEN(REPLACE(names, ';', '')) + 1
FROM Normalize
UNION ALL
SELECT s.String
, WordCounter = s.WordCounter + 1
, NWordStart = s.NWordEnd + 1
, NWordEnd = COALESCE(NULLIF(CHARINDEX(';', s.String, NWordEnd + 1), 0)
, LEN(s.String) + 1)
, Word = LTRIM(Cast(SubString(String, s.NWordStart, s.NWordEnd - s.NWordStart)
AS nvarchar(255)))
, WordNumber = s.WordNumber
FROM Splitter s
WHERE s.WordCounter + 1 <= s.WordNumber
)
SELECT LEFT(WORD , CHARINDEX(' ', CONCAT(Word, ' ')) - 1) Word
FROM Splitter
WHERE Word <> '';
SQLFiddle Demo
The CTE Normalize change all the separator char to ; to have a single separator for the split.
The CTE Splitter split the string into chunk using the ; as the separator.
The main query remove the stage information searching for the space between the name and the left bracket.
Possible inputs:
Hello World
La la, la la
Jack Bundy
I want to get into a variable the string BEFORE the first empty string ' '.
'Hello' or 'La' or 'Jack' accordingly.
How would I go about doing this?
Simplest (without dealing with my comment) is:
SELECT LEFT(#string, CHARINDEX(' ', #string));
You also need to cater for the case where the string doesn't contain a space. One way is as follows, assuming that #string can be at most 255 characters:
SELECT LEFT(#string, COALESCE(NULLIF(CHARINDEX(' ', #string), 0), 255));
These will leave a trailing space if a space is found. If you need to, you can get rid of that easily by wrapping the entire expression in LTRIM():
SELECT LTRIM(LEFT(#string, COALESCE(NULLIF(CHARINDEX(' ', #string), 0), 255)));
Or by subtracting one from the position where the space is found:
SELECT LEFT(#string, COALESCE(NULLIF(CHARINDEX(' ', #string)-1, -1), 255));
DECLARE #v AS VARCHAR(MAX) = 'Hello world'
SELECT SUBSTRING(#v, 0, CHARINDEX(' ', #v))