Replacing special characters and double spaces - sql

We have a string, 'AMERICAN:BEER~ INVENTIONS CHOCOLATE-FEVER'.
We are trying to remove special characters and replace that with a space and later checking if we have created any double spaces, and we try to replace the double spaces with a single space.
So, if we remove the special characters, and we remove the double spaces, we are left with 'AMERICAN BEER INVENTIONS CHOCOLATE FEVER'.
The problem here is, we have unintentionally removed, the default double space between 'INVENTIONS CHOCOLATE'.
How can we avoid this?
My current approach:
Remove special characters:
UPDATE xxxx.xxxxx
SET xxxx = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(xxxx, '<', ' '), '>', ' '), '(', ' '), ')', ' '), ':', ' '), '#', ' '), '~', ' ')
WHERE xxxx LIKE '%[<>:()#~]%';
Pass the column in a function to remove double spaces:
SET #str = TRIM(#str);
WHILE CHARINDEX(' ', #str) > 0
SET #str = REPLACE(#str, ' ', ' ');

Does the following work for you?
Using translate to convert to a single character, then remove additional spaces and finally replace the unwanted character:
declare #s varchar(50) = 'AMERICAN:BEER ~ INVENTIONS CHOCOLATE-FEVER'
select Replace(Replace(Replace(Translate(#s, '<>:()~-','#######'), '# ', '#'), ' #', '#'), '#', ' ');
Result
AMERICAN BEER INVENTIONS CHOCOLATE FEVER

Related

Regex to replace space with dash, spacedash, dotspace, dot and apostrophe with empty strings

I'm looking for a better way to write the following SQL statement whether using REGEX or any other way.
SELECT LOWER(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SCHOOL_NAME, ' -', ''), '. ', ''), '''', ''), '.', ''), ' ', '-'))
My intent is to apply these transformations:
Replacing Space with Dash
Replacing SpaceDash with Empty String
Replacing Apostrophe with Empty String
Replacing DotSpace with Empty String
Replacing Dot with Empty String
Sample of strings I'm dealing with include double space, apostrophe, dashes:
James valley court ad
Saint's lee park school
Harrison lodge - and hospital
I need these strings to become like:
james-valley-court-ad
saints-lee-park-school
harrison-lodge-and-hospital
Use regexp_replace:
SELECT REGEXP_REPLACE(REPLACE(LOWER(SCHOOL_NAME), '''', ''), '[ .-]+', '-')
See live demo.
To convert all non-letter characters to hyphens:
SELECT REGEXP_REPLACE(REPLACE(LOWER(SCHOOL_NAME), '''', ''), '[^a-z]+', '-')
See live demo.
Both options produce the following from your input:
james-valley-court-ad
saints-lee-park-school
harrison-lodge-and-hospital

MS SQL 2012 remove repeated characters from only Right and Left

I need stripe repeated characters from left and right only.
From:
,,,,2000001,2000002,2000003,2000004,2000005,2000006,,,,,
To:
2000001,2000002,2000003,2000004,2000005,2000006
Cheat with trim:
REPLACE(RTRIM(LTRIM(REPLACE(fld, ',', ' '))), ' ', ',')
Use LEFT, SUBSTRING and CHARINDEX string functions
Try this
DECLARE #str VARCHAR(500) = ',,,,2000001,2000002,2000003,2000004,2000005,2000006,,,,,'
SELECT LEFT(intr, Charindex(',,', intr) - 1) as Result
FROM (SELECT Substring(#str, Patindex('%[0-9]%', #str), Len(#str)) AS intr) a
Here is another solution using just REPLACE :) - so funny:
select replace(replace(replace(',,' + YourField + ',,', ',,', '.'), '.,', ''), '.', '')
The character . should not be present in the value of your field, so you can choose any other character meeting that requirement.
This approach is even usable when your field contains spaces (then you cannot play the trick with RTRIM and LTRIM).

How to Trim leading and trailing tab spaces in MSSQL query

I have data which has leading and trailing spaces in the string. when storing that data in database I want to trim the space in query itself before storing into DB.
Normal spaces are trimming properly with RTRIM and LTRIM function but if a string contains tab space,its not trimming the tab space from the input string.
Can anyone help me to get the string with trimmed with tab space from leading and trailing.
Replace the ASCII code for tab (9):
replace(#str, char(9), '')
To only remove the outer tabs, first change them to something that won't exist in your data (I use a series of four spaces in this example), then rtrim/ltrim, then convert that same sequence back to tabs:
replace(ltrim(rtrim(replace(#str, char(9), ' '))),' ', char(9));
Try this:
DECLARE #InputString nvarchar(50) = CHAR(9) + CHAR(9) + ' 123'+ 'abc ' + CHAR(9);
SELECT #InputString AS InputString
,REVERSE(RIGHT(REVERSE(RIGHT(#InputString, LEN(#InputString) - PATINDEX('%[^'+CHAR(9)+']%', #InputString) + 1)), LEN(REVERSE(RIGHT(#InputString, LEN(#InputString) - PATINDEX('%[^'+CHAR(9)+']%', #InputString) + 1))) - PATINDEX('%[^'+CHAR(9)+']%', REVERSE(RIGHT(#InputString, LEN(#InputString) - PATINDEX('%[^'+CHAR(9)+']%', #InputString) + 1))) + 1)) AS OutputString
;
Maybe you should refactor it as a function. Note, it may works only above Sql Server 2008. You can replace CHAR(9) to any character you like to trim.

String Concatenation with comma

I am trying to build the string with comma but I get extra space. How can I remove extra space between zipcode and country_name? Here is my string. Thank you for any suggestion.
SELECT
(COALESCE(address + ', ', '') +
COALESCE(city + ', ', '') +
COALESCE(state_code + ' ', '') +
COALESCE(zipcode + ' ', '') +
COALESCE(country_name + '', '')) address
from table1
where a_id = 2
Here is the result:
tewt, test ct, DE 4444 United States
You can use the RTRIM function which remove white space from right side of the variable. Check also LTRIM for the left cases.
I would change table column datatape to varchar(x) from char(x) or to nvarchar(x) from nchar(x). And change the data so they dont contain spaces. Just have to do that once and make changes so that app is not storing white spaces anymore.
char(x) and nchar(x) i would use just when there is fixed length strings, but this does not seem to be the case.

How do I combine trim and replace functions to remove spaces anywhere in the string?

I have this function (TRIM_REPLACE) that gets spaces from both the right and the left of a string. However, I am trying to modify it so that it trims in the middle also but I would rather combine the function than to do it separately.
Example: Let's say I have a name
Input
--------------------------
Peter<space><space>Griffin
<space> indicate one blank space in the above input.
I would like to trim the additional space in the so that it looks like this:
Output
--------------------------
Peter<space>Griffin
As you can see that the multiple spaces are replaced with a single space.
CREATE FUNCTION dbo.TRIM_REPLACE
(
#STRING VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
BEGIN
RETURN LTRIM(RTRIM(#STRING)) + REPLACE(#STRING, ' ',' ')
END
GO
How do I accomplish this?
If you are only concerned about pairs of spaces, you can use . . .
ltrim(rtrim(replace(#String, ' ', ' ')))
If you might have multiple spaces, you need to put this into a loop:
while charindex(' ', #string) > 0
begin
set #string = replace(#string, ' ', ' ');
end;
return ltrim(rtrim(#string));