6
Considering a variable with a text in SQL Server
. How can I remove 2 or more spaces within the text? In this case leaving only 1 space.
For example:
'1 tigre, 2 tigres, 3 tigres'
It should result in:
'1 tigre, 2 tigres, 3 tigres'
6
Considering a variable with a text in SQL Server
. How can I remove 2 or more spaces within the text? In this case leaving only 1 space.
For example:
'1 tigre, 2 tigres, 3 tigres'
It should result in:
'1 tigre, 2 tigres, 3 tigres'
9
Do so:
declare @texto varchar(MAX)
set @texto = '1 tigre, 2 tigres, 3 tigres'
set @texto = replace(replace(replace(@texto,' ','<>'),'><',''),'<>',' ')
select @texto
Exit:
1 tiger, 2 tigers, 3 tigers
Explanation:
<>
. replace(@texto,' ','<>')
, will result in: 1<>tigre,<>2<><>tigres,<>3<><><>tigres><
for ''
. replace('1<>tigre,<>2<><>tigres,<>3<><><>tigres','><','')
, will result in: 1<>tiger,<>2<>tigers,<>3<>tigers <>
by spaces(' '
). replace('1<>tigre,<>2<>tigres,<>3<>tigres','<>',' ')
, will result in: 1 tiger, 2 tigers, 3 tigersNote: Replace works in virtually all languages or almost all. So this solution can be applicable to many cases.
With the encouragement of @Jefferson Quesado and Udemy’s Course on Regexp added another example using Regex
.
/[]{2,}/
to search for two or more occurrences of blank spaces.Replace
and replace with nothing.Query:
declare @texto varchar(MAX)
set @texto = '1 tigre, 2 tigres, 3 tigres'
set @texto = replace(@texto,'','/[]{2,}/')
select @texto
This method is interesting because it works in virtually any language
@Sorack yes since replace is found in almost all languages. Good that I could help :)
@Marconi, do you know of regular expression in TSQL to solve this? I believe that if you have it you can solve it in a more satisfactory way, cleaner to read, at least
@Jeffersonquesado is a subject yet I have to study, but I tried to leave as detailed as possible the answer, putting as each replace will as a result. :)
It may seem like a sledgehammer to some, but in my opinion it’s a simple and effective way to solve the problem!
From what I understood of the first solution if the original string contains ><
they will be lost at the end.
Browser other questions tagged sql database sql-server
You are not signed in. Login or sign up in order to post.
You want to leave only 1 space or none?
– Marconi
@Marconi only 1 even
– Sorack