Replace Funny Character in a String in SQL Server - sql

I need help to replace funny character in a column in SQL Server,
I have data like this:
id itemDesc
----------------------------------------------
1 Ball lock pins/ spring typeáááááá
2 Res 1.5k Ohm û R0805 1%
If itemDesc contains á, then replace it with " "; if it contains (û), replace it with -. I used charindex but not change at all especially with many funny characters like id = 1, so if i used charindex, "Ball lock pins/ spring typeáááááá" => "Ball lock pins/ spring type ááááá"
Any approach?
thanks for help

You can use REPLACE to replace the characters on the string:
SELECT REPLACE(REPLACE(itemDesc, 'á', ' '), 'û', '-') FROM table_name
In case you want to UPDATE the value on column itemDesc you can use the following:
UPDATE table_name SET itemDesc = REPLACE(REPLACE(itemDesc, 'á', ' '), 'û', '-')
The function CHARINDEX can't be used to replace the characters, but to find them. So you can UPDATE or SELECT only the rows with these characters using CHARINDEX:
SELECT REPLACE(REPLACE(itemDesc, 'á', ' '), 'û', '-')
FROM table_name
WHERE CHARINDEX('á', itemDesc) > 0 OR CHARINDEX('û', itemDesc) > 0
UPDATE table_name SET itemDesc = REPLACE(REPLACE(itemDesc, 'á', ' '), 'û', '-')
WHERE CHARINDEX('á', itemDesc) > 0 OR CHARINDEX('û', itemDesc) > 0
demo: http://www.sqlfiddle.com/#!18/6e241/1/0

If you're using SQL Server 2017, you can use TRANSLATE:
SELECT TRANSLATE(itemDesc, 'áû',' -') AS itemDescTidy
FROM table_name;
This is a little more succinct than a nested REPLACE (but is actually identical, as it's a "short-hand" function).

Related

Any way to change specific data in a column e.g Mr to Dr which contains a name

I am trying to change the Titles of 'doctors' in a database and was just wondering was there a SQL query which I could run to change them.
The column im trying to change
What I am asking is that there is any way I can update the column to add a 'Dr' infront of the names to replace the 'Miss','Mr' etc.
I'm thinking about using a SQL Statement containing the wildcard function to update it but not sure it would change the specifics.
Thanks,
Karl
Use REPLACE option
UPDATE table_name
SET column_name = REPLACE(column_name, 'Mr.', 'Dr.')
WHERE column_name LIKE 'Mr.%'
try this
Update myTable
set name = replace(replace(name,'Miss ','Dr '),'Mr ','Dr ')
I might suggest doing:
update t
set col = stuff(col, 1, charindex(' ', col + ' '), 'Dr');
This only replaces the first word in the string. You might want to be extra careful and add a where clause.
update t
set col = stuff(col, 1, charindex(' ', col + ' '), 'Dr')
where col like 'Miss %' or col like 'Mr %' or
col like 'Mrs %' or col like 'Ms %';
The problem with replace() is that it replaces all occurrences in the string. Although the honorifics are unlikely to be in a name, you could have names like "Missy Elliott".

How to replace all the dots before # in an email with empty string in Oracle SQL?

I want to replace all the dots before # in an email with empty string in oracle query
like:
anurag.mart#hotmail.com >> anuragmart#hotmail.com
Instr - To identify the position(#)
Substr - To extract data between start(1) and end(#) position
Replace - To replace . with ''
|| - To concatenate two strings
Try this
SELECT Replace(Substr('anurag.mart#hotmail.com', 1,
Instr('anurag.mart#hotmail.com', '#', 1)), '.', '')
|| Substr('anurag.mart#hotmail.com', Instr('anurag.mart#hotmail.com','#')+1)
FROM dual
Result:
anuragmart#hotmail.com
SqlFiddle Demo
The easiest way is to use REGEXP_REPLACE to identify the pattern and replace it with required pattern.
regexp_replace('anurag.mart#hotmail.com', '(\w+)\.(\w+)(#+)', '\1\2\3')
For example,
SQL> SELECT 'anurag.mart#hotmail.com' email_id,
2 regexp_replace('anurag.mart#hotmail.com', '(\w+)\.(\w+)(#+)', '\1\2\3') new_email_id
3 FROM dual;
EMAIL_ID NEW_EMAIL_ID
----------------------- ----------------------
anurag.mart#hotmail.com anuragmart#hotmail.com
I came on this page while looking for solutions for SQL servers, I converted the above for SQL server for my project, Here is SQL if anybody else needs it.
SELECT
CONCAT(
REPLACE(
SUBSTRING(EmailAddress, 1, CHARINDEX('#', EmailAddress)-1),
'.',
''
),
SUBSTRING(EmailAddress, CHARINDEX('#', EmailAddress), LEN(EmailAddress))
)
FROM [Applicant]

Update statement to update part of column length

I'm working on SQL Server 2008. Assume the following column.
column1
cjd.001 306.1
cjd.001 306.2
cjd.001 306.R
Now i want to replace all '.' with '-'. But just from first string i.e. before space or below 8 characters. The remaining field should remain same.
SampleOutput
cjd-001 306.1
cjd-001 306.2
cjd-001 306.R
I tried below query but it replaces all '.'.
UPDATE dbo.table
SET column1 = REPLACE(column1, '.', '-')
I want to know what can i use in where clause?
Tried using substring function but it didn't work.
I think you need a SQL like this:
UPDATE yourTable
SET column1 = REPLACE(SUBSTRING(column1, 1, CHARINDEX(' ', column1)), '.', '-')
+ SUBSTRING(column1, CHARINDEX(' ', column1) + 1, LEN(column1));
[SQL Fiddle Demo]

Oracle update multiple spaces in a column with a single space

I'm trying to update a column that could possibly have a single space or multiple spaces into just one single space using a plain sql statement not pl sql
I could do it through update table set column_name='' where column_name like '% %'
However, there could be some data such as abc def in that column. I do not want to disturb the pattern of that data meaning if want to do it only when the column is filled with white space and not touch columns that have any data.
I would recommend using a regular expression to do this, both to do the replacement and to do the matching:
UPDATE mytable
SET mycolumn = REGEXP_REPLACE(mycolumn, '\s{2,}', ' ')
WHERE REGEXP_LIKE(mycolumn, '\s{2,}')
This will replace two or more consecutive whitespace characters (spaces, tabs, etc.) with a single space. If you just want to replace spaces and not tabs, carriage returns, or newlines, use the following:
UPDATE mytable
SET mycolumn = REGEXP_REPLACE(mycolumn, ' {2,}', ' ')
WHERE REGEXP_LIKE(mycolumn, ' {2,}')
The reason for using {2,} is so that we don't bother replacing spaces where it need not be done.
With regular expression:
update table set column=regexp_replace(column, ' +', ' ')
Try:
update mytable
set col = ' '
where replace (col, ' ', null) is null;
I have used regexp_like to solve this
update table set column= ' '
where column in (select column from table where regexp_like('column','^\s+$')
Thanks
Try this:
update product set name = replace(name, ' ', ' ') where name like '% %';
where the second parameter of replace expression and like ('% %') contains two blank spaces.
In my case, the result was:
TENIS NIKE AIR => TENIS NIKE AIR
TENIS NIKE MAN => TENIS NIKE MAN

How can I remove leading and trailing quotes in SQL Server?

I have a table in a SQL Server database with an NTEXT column. This column may contain data that is enclosed with double quotes. When I query for this column, I want to remove these leading and trailing quotes.
For example:
"this is a test message"
should become
this is a test message
I know of the LTRIM and RTRIM functions but these workl only for spaces. Any suggestions on which functions I can use to achieve this.
I have just tested this code in MS SQL 2008 and validated it.
Remove left-most quote:
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 2, LEN(FieldName))
WHERE LEFT(FieldName, 1) = '"'
Remove right-most quote: (Revised to avoid error from implicit type conversion to int)
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 1, LEN(FieldName)-1)
WHERE RIGHT(FieldName, 1) = '"'
I thought this is a simpler script if you want to remove all quotes
UPDATE Table_Name
SET col_name = REPLACE(col_name, '"', '')
You can simply use the "Replace" function in SQL Server.
like this ::
select REPLACE('this is a test message','"','')
note: second parameter here is "double quotes" inside two single quotes and third parameter is simply a combination of two single quotes. The idea here is to replace the double quotes with a blank.
Very simple and easy to execute !
My solution is to use the difference in the the column values length compared the same column length but with the double quotes replaced with spaces and trimmed in order to calculate the start and length values as parameters in a SUBSTRING function.
The advantage of doing it this way is that you can remove any leading or trailing character even if it occurs multiple times whilst leaving any characters that are contained within the text.
Here is my answer with some test data:
SELECT
x AS before
,SUBSTRING(x
,LEN(x) - (LEN(LTRIM(REPLACE(x, '"', ' ')) + '|') - 1) + 1 --start_pos
,LEN(LTRIM(REPLACE(x, '"', ' '))) --length
) AS after
FROM
(
SELECT 'test' AS x UNION ALL
SELECT '"' AS x UNION ALL
SELECT '"test' AS x UNION ALL
SELECT 'test"' AS x UNION ALL
SELECT '"test"' AS x UNION ALL
SELECT '""test' AS x UNION ALL
SELECT 'test""' AS x UNION ALL
SELECT '""test""' AS x UNION ALL
SELECT '"te"st"' AS x UNION ALL
SELECT 'te"st' AS x
) a
Which produces the following results:
before after
-----------------
test test
"
"test test
test" test
"test" test
""test test
test"" test
""test"" test
"te"st" te"st
te"st te"st
One thing to note that when getting the length I only need to use LTRIM and not LTRIM and RTRIM combined, this is because the LEN function does not count trailing spaces.
I know this is an older question post, but my daughter came to me with the question, and referenced this page as having possible answers. Given that she's hunting an answer for this, it's a safe assumption others might still be as well.
All are great approaches, and as with everything there's about as many way to skin a cat as there are cats to skin.
If you're looking for a left trim and a right trim of a character or string, and your trailing character/string is uniform in length, here's my suggestion:
SELECT SUBSTRING(ColName,VAR, LEN(ColName)-VAR)
Or in this question...
SELECT SUBSTRING('"this is a test message"',2, LEN('"this is a test message"')-2)
With this, you simply adjust the SUBSTRING starting point (2), and LEN position (-2) to whatever value you need to remove from your string.
It's non-iterative and doesn't require explicit case testing and above all it's inline all of which make for a cleaner execution plan.
The following script removes quotation marks only from around the column value if table is called [Messages] and the column is called [Description].
-- If the content is in the form of "anything" (LIKE '"%"')
-- Then take the whole text without the first and last characters
-- (from the 2nd character and the LEN([Description]) - 2th character)
UPDATE [Messages]
SET [Description] = SUBSTRING([Description], 2, LEN([Description]) - 2)
WHERE [Description] LIKE '"%"'
You can use following query which worked for me-
For updating-
UPDATE table SET colName= REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') WHERE...
For selecting-
SELECT REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') FROM TableName
you could replace the quotes with an empty string...
SELECT AllRemoved = REPLACE(CAST(MyColumn AS varchar(max)), '"', ''),
LeadingAndTrailingRemoved = CASE
WHEN MyTest like '"%"' THEN SUBSTRING(Mytest, 2, LEN(CAST(MyTest AS nvarchar(max)))-2)
ELSE MyTest
END
FROM MyTable
Some UDFs for re-usability.
Left Trimming by character (any number)
CREATE FUNCTION [dbo].[LTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(LTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Right Trimming by character (any number)
CREATE FUNCTION [dbo].[RTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(RTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Note the dummy character '¦' (Alt+0166) cannot be present in the data (you may wish to test your input string, first, if unsure or use a different character).
To remove both quotes you could do this
SUBSTRING(fieldName, 2, lEN(fieldName) - 2)
you can either assign or project the resulting value
You can use TRIM('"' FROM '"this "is" a test"') which returns: this "is" a test
CREATE FUNCTION dbo.TRIM(#String VARCHAR(MAX), #Char varchar(5))
RETURNS VARCHAR(MAX)
BEGIN
RETURN SUBSTRING(#String,PATINDEX('%[^' + #Char + ' ]%',#String)
,(DATALENGTH(#String)+2 - (PATINDEX('%[^' + #Char + ' ]%'
,REVERSE(#String)) + PATINDEX('%[^' + #Char + ' ]%',#String)
)))
END
GO
Select dbo.TRIM('"this is a test message"','"')
Reference : http://raresql.com/2013/05/20/sql-server-trim-how-to-remove-leading-and-trailing-charactersspaces-from-string/
I use this:
UPDATE DataImport
SET PRIO =
CASE WHEN LEN(PRIO) < 2
THEN
(CASE PRIO WHEN '""' THEN '' ELSE PRIO END)
ELSE REPLACE(PRIO, '"' + SUBSTRING(PRIO, 2, LEN(PRIO) - 2) + '"',
SUBSTRING(PRIO, 2, LEN(PRIO) - 2))
END
Try this:
SELECT left(right(cast(SampleText as nVarchar),LEN(cast(sampleText as nVarchar))-1),LEN(cast(sampleText as nVarchar))-2)
FROM TableName