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
Related
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 one column for comment and I need to show this for one report.
Here what happen some time, users uses multiple enters in comment box. I can not access code part I need to manage this thing in SQL only.
So I have removed unwanted
1 /r/n
2 /n/n
from using
REPLACE(REPLACE(Desc, CHAR(13)+CHAR(10), CHAR(10)),CHAR(10)+CHAR(10), CHAR(10)) as Desc,
Now I want to remove any \r or \n from starting or ending of the string if any
By the way you meant in your question:(Remove char(10) or char(13) from specific string)
Note: You should see the output result by switching your resultset output to Results to Text(Ctrl+T).
Results to Text
Results to Grid
Use TRIM check here
Example : UPDATE tablename SET descriptions = TRIM(TRAILING "<br>" FROM descriptions)
if you want to replace newline then use something like below
SELECT REPLACE(REPLACE(#str, CHAR(13), ''), CHAR(10), '')
or
DECLARE #testString varchar(255)
set #testString = 'MY STRING '
/*Select the string and try to copy and paste into notepad and tab is still there*/
SELECT testString = #testString
/*Ok, it seems easy, let's try to trim this. Huh, it doesn't work, the same result here.*/
SELECT testStringTrim = RTRIM(#testString)
/*Let's try to get the size*/
SELECT LenOfTestString = LEN(#testString)
/*This supposed to give us string together with blank space, but not for tab though*/
SELECT DataLengthOfString= DATALENGTH(#testString)
SELECT ASCIIOfTab = ASCII(' ')
SELECT CHAR(9)
/*I always use this like a final solution*/
SET #testString = REPLACE(REPLACE(REPLACE(#testString, CHAR(9), ''), CHAR(10), ''), CHAR(13), '') SELECT #testString
/*
CHAR(9) - Tab
CHAR(10) - New Line
CHAR(13) - Carriage Return
*/
Reference
select dbo.trim('abc','c') -- ab
select dbo.trim('abc','a') -- bc
select dbo.trim(' b ',' ') -- b
Create a user-define-function: trim()
trim from both sides
trim any letter: space, \r, \n, etc
Create FUNCTION Trim
(
#Original varchar(max), #letter char(1)
)
RETURNS varchar(max)
AS
BEGIN
DECLARE #rtrim varchar(max)
SELECT #rtrim = iif(right(#original, 1) = #letter, left(#original,datalength(#original)-1), #original)
return iif( left(#rtrim,1) = #letter, right(#rtrim,datalength(#rtrim)-1),#rtrim)
END
I have a short string of alphanumeric characters A-Z and 0-9
Both Characters AND Numbers are included in the string.
I want to strip spaces, and compare each string against a 'pattern' of which it will match only one. The Patterns use A to denote any character A-Z and 9 for any 0-9.
The 6 patterns are:
A99AA
A999AA
A9A9AA
AA99AA
AA999AA
AA9A9AA
I have these in a table with another column, with the correct space in place :-
pattern PatternTrimmed
A9 9AA A99AA
A99 9AA A999AA
A9A 9AA A9A9AA
AA9 9AA AA99AA
AA99 9AA AA999AA
AA9A 9AA AA9A9AA
I am using SQL Server 2005, and I don't want to have 34 replace statements changing each of the characters and numbers to A's and 9's.
Suggestions on how I can achieve this in a short succinct way, please.
Here's what I want to avoid :-
update postcodes set Pattern = replace (Pattern, 'B', 'A')
update postcodes set Pattern = replace (Pattern, 'C', 'A')
update postcodes set Pattern = replace (Pattern, 'D', 'A')
update postcodes set Pattern = replace (Pattern, 'E', 'A')
etc.
and
update postcodes set Pattern = replace (Pattern, '0', '9')
update postcodes set Pattern = replace (Pattern, '1', '9')
update postcodes set Pattern = replace (Pattern, '2', '9')
etc
Basically, I am trying to take a UK postcode typed in at a call centre by an imbecile, and pattern match the entered postcode against one of the 6 above patterns, and work out where to insert the space.
What about something like this:
Declare #table table
(
ColumnToCompare varchar(20),
AmendedValue varchar(20)
)
Declare #patterns table
(
Pattern varchar(20),
TrimmedPattern varchar(20)
)
Insert Into #table (ColumnToCompare)
Select 'BBB87 BBB'
Union all
Select 'J97B B'
union all
select '282 8289'
union all
select 'UW83 7YY'
union all
select 'UW83 7Y0'
Insert Into #patterns
Select 'A9 9AA', 'A99AA'
union all
Select 'A99 9AA', 'A999AA'
union all
Select 'A9A 9AA', 'A9A9AA'
union all
Select 'AA9 9AA', 'AA99AA'
union all
Select 'AA99 9AA', 'AA999AA'
union all
Select 'AA9A 9AA', 'AA9A9AA'
Update #table
Set AmendedValue = Left(Replace(ColumnToCompare, ' ',''), (CharIndex(' ', Pattern)-1)) + space(1) +
SubString(Replace(ColumnToCompare, ' ',''), (CharIndex(' ', Pattern)), (Len(ColumnToCompare) - (CharIndex(' ', Pattern)-1)))
From #table
Cross Join #Patterns
Where PatIndex(Replace((Replace(TrimmedPattern, 'A','[A-Z]')), '9','[0-9]'), Replace(ColumnToCompare, ' ' ,'')) > 0
select * From #table
This part
Left(Replace(ColumnToCompare, ' ',''), (CharIndex(' ', Pattern)-1))
finds the space in the pattern that has been matched and takes the left hand portion of the string being compared.
it then adds a space
+ space(1) +
then this part
SubString(Replace(ColumnToCompare, ' ',''), (CharIndex(' ', Pattern)), (Len(ColumnToCompare) - (CharIndex(' ', Pattern)-1)))
appends the remainder of the string to the new value.
I need to ensure that a given field does not have more than one space (I am not concerned about all white space, just space) between characters.
So
'single spaces only'
needs to be turned into
'single spaces only'
The below will not work
select replace('single spaces only',' ',' ')
as it would result in
'single spaces only'
I would really prefer to stick with native T-SQL rather than a CLR based solution.
Thoughts?
Even tidier:
select string = replace(replace(replace(' select single spaces',' ','<>'),'><',''),'<>',' ')
Output:
select single spaces
This would work:
declare #test varchar(100)
set #test = 'this is a test'
while charindex(' ',#test ) > 0
begin
set #test = replace(#test, ' ', ' ')
end
select #test
If you know there won't be more than a certain number of spaces in a row, you could just nest the replace:
replace(replace(replace(replace(myText,' ',' '),' ',' '),' ',' '),' ',' ')
4 replaces should fix up to 16 consecutive spaces (16, then 8, then 4, then 2, then 1)
If it could be significantly longer, then you'd have to do something like an in-line function:
CREATE FUNCTION strip_spaces(#str varchar(8000))
RETURNS varchar(8000) AS
BEGIN
WHILE CHARINDEX(' ', #str) > 0
SET #str = REPLACE(#str, ' ', ' ')
RETURN #str
END
Then just do
SELECT dbo.strip_spaces(myText) FROM myTable
This is somewhat brute force, but will work
CREATE FUNCTION stripDoubleSpaces(#prmSource varchar(max)) Returns varchar(max)
AS
BEGIN
WHILE (PATINDEX('% %', #prmSource)>0)
BEGIN
SET #prmSource = replace(#prmSource ,' ',' ')
END
RETURN #prmSource
END
GO
-- Unit test --
PRINT dbo.stripDoubleSpaces('single spaces only')
single spaces only
update mytable
set myfield = replace (myfield, ' ', ' ')
where charindex(' ', myfield) > 0
Replace will work on all the double spaces, no need to put in multiple replaces. This is the set-based solution.
It can be done recursively via the function:
CREATE FUNCTION dbo.RemSpaceFromStr(#str VARCHAR(MAX)) RETURNS VARCHAR(MAX) AS
BEGIN
RETURN (CASE WHEN CHARINDEX(' ', #str) > 0 THEN
dbo.RemSpaceFromStr(REPLACE(#str, ' ', ' ')) ELSE #str END);
END
then, for example:
SELECT dbo.RemSpaceFromStr('some string with many spaces') AS NewStr
returns:
NewStr
some string with many spaces
Or the solution based on method described by #agdk26 or #Neil Knight (but safer)
both examples return output above:
SELECT REPLACE(REPLACE(REPLACE('some string with many spaces'
, ' ', ' ' + CHAR(7)), CHAR(7) + ' ', ''), ' ' + CHAR(7), ' ') AS NewStr
--but it remove CHAR(7) (Bell) from string if exists...
or
SELECT REPLACE(REPLACE(REPLACE('some string with many spaces'
, ' ', ' ' + CHAR(7) + CHAR(7)), CHAR(7) + CHAR(7) + ' ', ''), ' ' + CHAR(7) + CHAR(7), ' ') AS NewStr
--but it remove CHAR(7) + CHAR(7) from string
How it works:
Caution:
Char/string used to replace spaces shouldn't exist on begin or end of string and stand alone.
Here is a simple function I created for cleaning any spaces before or after, and multiple spaces within a string. It gracefully handles up to about 108 spaces in a single stretch and as many blocks as there are in the string. You can increase that by factors of 8 by adding additional lines with larger chunks of spaces if you need to. It seems to perform quickly and has not caused any problems in spite of it's generalized use in a large application.
CREATE FUNCTION [dbo].[fnReplaceMultipleSpaces] (#StrVal AS VARCHAR(4000))
RETURNS VARCHAR(4000)
AS
BEGIN
SET #StrVal = Ltrim(#StrVal)
SET #StrVal = Rtrim(#StrVal)
SET #StrVal = REPLACE(#StrVal, ' ', ' ') -- 16 spaces
SET #StrVal = REPLACE(#StrVal, ' ', ' ') -- 8 spaces
SET #StrVal = REPLACE(#StrVal, ' ', ' ') -- 4 spaces
SET #StrVal = REPLACE(#StrVal, ' ', ' ') -- 2 spaces
SET #StrVal = REPLACE(#StrVal, ' ', ' ') -- 2 spaces (for odd leftovers)
RETURN #StrVal
END
Method #1
The first method is to replace extra spaces between words with an uncommon symbol combination as a temporary marker. Then you can replace the temporary marker symbols using the replace function rather than a loop.
Here is a code example that replaces text within a String variable.
DECLARE #testString AS VARCHAR(256) = ' Test text with random* spacing. Please normalize this spacing!';
SELECT REPLACE(REPLACE(REPLACE(#testString, ' ', '*^'), '^*', ''), '*^', ' ');
Execution Time Test #1: In ten runs of this replacement method, the average wait time on server replies was 1.7 milliseconds and total execution time was 4.6 milliseconds.
Execution Time Test #2: The average wait time on server replies was 1.7 milliseconds and total execution time was 3.7 milliseconds.
Method #2
The second method is not quite as elegant as the first, but also gets the job done. This method works by nesting four (or optionally more) replace statements that replace two blank spaces with one blank space.
DECLARE #testString AS VARCHAR(256) = ' Test text with random* spacing. Please normalize this spacing!';
SELECT REPLACE(REPLACE(REPLACE(REPLACE(#testString,' ',' '),' ',' '),' ',' '),' ',' ')
Execution Time Test #1: In ten runs of this replacement method, the average wait time on server replies was 1.9 milliseconds and total execution time was 3.8 milliseconds.
Execution Time Test #2: The average wait time on server replies was 1.8 milliseconds and total execution time was 4.8 milliseconds.
Method #3
The third method of replacing extra spaces between words is to use a simple loop. You can do a check on extra spaces in a while loop and then use the replace function to reduce the extra spaces with each iteration of the loop.
DECLARE #testString AS VARCHAR(256) = ' Test text with random* spacing. Please normalize this spacing!';
WHILE CHARINDEX(' ',#testString) > 0
SET #testString = REPLACE(#testString, ' ', ' ')
SELECT #testString
Execution Time Test #1: In ten runs of this replacement method, the average wait time on server replies was 1.8 milliseconds and total execution time was 3.4 milliseconds.
Execution Time Test #2: The average wait time on server replies was 1.9 milliseconds and total execution time was 2.8 milliseconds.
This is the solution via multiple replace, which works for any strings (does not need special characters, which are not part of the string).
declare #value varchar(max)
declare #result varchar(max)
set #value = 'alpha beta gamma delta xyz'
set #result = replace(replace(replace(replace(replace(replace(replace(
#value,'a','ac'),'x','ab'),' ',' x'),'x ',''),'x',''),'ab','x'),'ac','a')
select #result -- 'alpha beta gamma delta xyz'
You can try this:
select Regexp_Replace('single spaces only','( ){2,}', ' ') from dual;
Just Adding Another Method-
Replacing Multiple Spaces with Single Space WITHOUT Using REPLACE in SQL Server-
DECLARE #TestTable AS TABLE(input VARCHAR(MAX));
INSERT INTO #TestTable VALUES
('HAPPY NEWYEAR 2020'),
('WELCOME ALL !');
SELECT
CAST('<r><![CDATA[' + input + ']]></r>' AS XML).value('(/r/text())[1] cast as xs:token?','VARCHAR(MAX)')
AS Expected_Result
FROM #TestTable;
--OUTPUT
/*
Expected_Result
HAPPY NEWYEAR 2020
WELCOME ALL !
*/
Found this while digging for an answer:
SELECT REPLACE(
REPLACE(
REPLACE(
LTRIM(RTRIM('1 2 3 4 5 6'))
,' ',' '+CHAR(7))
,CHAR(7)+' ','')
,CHAR(7),'') AS CleanString
where charindex(' ', '1 2 3 4 5 6') > 0
The full answer (with explanation) was pulled from: http://techtipsbysatish.blogspot.com/2010/08/sql-server-replace-multiple-spaces-with.html
On second look, seems to be just a slightly different version of the selected answer.
Please Find below code
select trim(string_agg(value,' ')) from STRING_SPLIT(' single spaces only ',' ')
where value<>' '
This worked for me..
Hope this helps...
With the "latest" SQL Server versions (Compatibility level 130) you could also use string_split and string_agg.
string_split can return an ordinal column when provided with a third argument. (https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-ver16#enable_ordinal). So we can preserve the order of the string_split.
Using a common table expression:
with cte(value) as (select value from string_split(' a b c d e ', ' ', 1) where value <> '' order by ordinal offset 0 rows)
select string_agg(value, ' ') from cte
a b c d e results in a b c d e
I use FOR XML PATH solution to replace multiple spaces into single space
The idea is to replace spaces with XML tags
Then split XML string into string fragments without XML tags
Finally concatenating those string values by adding single space characters between two
Here is how final UDF function can be called
select dbo.ReplaceMultipleSpaces(' Sample text with multiple space ')