RTRIM a pattern, not all the characters - sql

I have strings like these:
JAPANNO
CHINANO
BROOKLYNNO
I want to delete the 'NO' from all of the strings. I tried this:
rtrim(string, 'NO')
but for example in the case of BROOKLYNNO, I got this:
BROOKLY.
It deletes all the N-s from the end. How can I delete just the pattern of 'NO'?
I know I can do it with substr, but the TechOnTheNet says there is a way to delete a pattern with RTRIM, and I really want to know the way.
Thank you in advance!

We may consider doing a regex replacement via REGEXP_REPLACE, if you give a context for when NO should be removed and when it should not. For example, if you wanted to remove NO from the ends of your strings only, we could do the following:
UPDATE yourTable
SET col = REGEXP_REPLACE(col, 'no$', '', 1, 0, 'i');

You could use TRIM(TRAILING ... FROM):
SELECT col_name,
REPLACE(TRIM(TRAILING '^' FROM REPLACE(col_name, 'NO', '^')), '^', 'NO') AS res
FROM tab;
DBFiddle Demo

Have a look at this, maybe?
declare #string varchar(150) = 'BROOKLYNNO'
select LEN(#string)
select LEFT(#string,(LEN(#string)-2))
You can then update your column with the output from the final select statement, which trims the last two letters from the string.
I suppose it might be worth asking how you're getting the data that you have here, strings appended with "NO"?

Related

Oracle remove special characters

I have a column in a table ident_nums that contains different types of ids. I need to remove special characters(e.g. [.,/#&$-]) from that column and replace them with space; however, if the special characters are found at the beginning of the string, I need to remove it without placing a space. I tried to do it in steps; first, I removed the special characters and replaced them with space (I used
REGEXP_REPLACE) then found the records that contain spaces at the beginning of the string and tried to use the TRIM function to remove the white space, but for some reason is not working that.
Here is what I have done
Select regexp_replace(id_num, '[:(),./#*&-]', ' ') from ident_nums
This part works for me, I remove all the unwanted characters from the column, however, if the string in the column starts with a character I don't want to have space in there, I would like to remove just the character, so I tried to use the built-in function TRIM.
update ident_nums
set id_num = TRIM(id_num)
I'm getting an error ORA-01407: can't update ident_nums.id_num to NULL
Any ideas what I am doing wrong here?
It does work if I add a where clause,
update ident_nums
set id_num = TRIM(id_num) where id = 123;
but I need to update all the rows with the white space at the beginning of the string.
Any suggestions are welcome.
Or if it can be done better.
The table has millions of records.
Thank you
Regexp can be slow sometimes so if you can do it by using built-in functions - consider it.
As #Abra suggested TRIM and TRANSLATE is a good choice, but maybe you would prefer LTRIM - removes only leading spaces from string (TRIM removes both - leading and trailing character ). If you want to remove "space" you can ommit defining the trim character parameter, space is default.
select
ltrim(translate('#kdjdj:', '[:(),./#*&-]', ' '))
from dual;
select
ltrim(translate(orginal_string, 'special_characters_to_remove', ' '))
from dual;
Combination of Oracle built-in functions TRANSLATE and TRIM worked for me.
select trim(' ' from translate('#$one,$2-zero...', '#$,-.',' ')) as RESULT
from DUAL
Refer to this dbfiddle
I think trim() is the key, but if you want to keep only alpha numerics, digits, and spaces, then:
select trim(' ' from regexp_replace(col, '[^a-zA-Z0-9 ]', ' ', 1, 0))
regexp_replace() makes it possible to specify only the characters you want to keep, which could be convenient.
Thanks, everyone, It this query worked for me
update update ident_nums
set id_num = LTRIM(REGEXP_REPLACE(id_num, '[:space:]+', ' ')
where REGEXP_LIKE(id_num, '^[ ?]')
this should work for you.
SELECT id_num, length(id_num) length_old, NEW_ID_NUM, length(NEW_ID_NUM) len_NEW_ID_NUM, ltrim(NEW_ID_NUM), length(ltrim(NEW_ID_NUM)) length_after_ltrim
FROM (
SELECT id_num, regexp_replace(id_num, '[:(),./#*&-#]', ' ') NEW_ID_NUM FROM
(
SELECT '1234$%45' as id_num from dual UNION
SELECT '#SHARMA' as id_num from dual UNION
SELECT 'JACK TEST' as id_num from dual UNION
SELECT 'XYZ#$' as id_num from dual UNION
SELECT '#ABCDE()' as id_num from dual -- THe 1st character is space
)
)

How to use Charindex for one or the other character

I have a string with a bunch of numbers but it contains one letter somewhere in the center of the string. This letter can either be 'A' or 'B'. I am trying to find out the position of this letter with the Charindex() function. However it doesn't work when you have two search parameters:
select charindex('[A,B]','190118A3700000')
I tried it out with a range and wildcards but it did not work. So what I want are these two separate queries combined in one:
select charindex('A','190118A3700000')
select charindex('B','190118A3700000')
Does anybody have an idea how to do this?
Thank you!!!
Use patindex():
select patindex('%[A,B]%', '190118A3700000')
Or, if you want the first non-digit:
select patindex('%[^0-9]%', '190118A3700000')
Here is a db<>fiddle.
charindex() does not understand wildcards.
If charindex doesn't find that character, it returns 0 so all you need to do is
select col, charindex('A', col) + charindex('B', col) as position
from your_table;
Another alternative
select col, charindex('A', replace(col, 'B', 'A')) as position
from your_table;
DEMO

SQL Server 2014: Add space after comma

I want to update only the values in Column1 that have characters of a string, then a comma, then (without a space) more characters, like so: abc,def or abc,123,def. I want a space to be added between the comma and the next character, like so: abc, def or abc, 123, def. It shouldn't add an extra space if there already is one.
Sorry, I don't have any existing SQL to show-- I'm not sure where to even start on this.
I'd first replace all instances of , (comma + space) with , (comma, NO space). That way everything is uniform. Then go the other way; replace commas with comma + space
Perhaps a little overkill, but this will support any combination of space(s) before and after a comma
Example
Declare #S varchar(max) = 'abc , 123 , def, ddd'
Select replace(replace(replace(replace(#S,',','<>'),' ','<>'),'><',''),'<>',', ')
Returns
abc, 123, def, ddd
I should add, this is a little trick from Gordon several months ago. I don't have the original link
This would do what you are wanting
UPDATE TABLE
SET Col1 = REPLACE(REPLACE(Col1,', ',','),',',', ')
WHERE Col1 LIKE '%,%'
I think you are need to first remove space and then add space to column1 near
UPDATE yt set yt.Column1 =replace(replace(yt.Column1 ,' ',''),',',', ')
from yourtable yt
where yt.Column1 like '%,%'
If one needs exactly one space after the comma and the data is not consistent there is also the option of a string_split and then string_agg:
DECLARE #test varchar(max) = 'Test, Test 12,Test34,Test56 , Test78'
select STRING_AGG(Trim(value),', ') as Test from string_split(#test,',')
Result:
Test, Test 12, Test34, Test56, Test78
If possible you should use the new "enable_ordinal" option of string_split, but i actually never had problems with the order.

Removing trailing spaces and whitespaces from SQL Server column

I have a column in my SQL Server database and it has white spaces from left and right site of the record. Basically it's a nvarchar(250) column.
I have tried removing white spaces completely like this:
UPDATE MyTable
SET whitespacecolumn = LTRIM(RTRIM(whitespacecolumn))
But this didn't work out at all, the whitespace is still there. What am I doing wrong here?
Check the below;
Find any special characters like char(10), char(13) etc in the field value.
Check the status of ANSI_PADDING ON. Refer this MSDN article.
I think replace is the way as you are looking to update
UPDATE MyTable SET whitespacecolumn = Replace(whitespacecolumn, ' ', '')
you can try doing select first and then prefer to update
SELECT *, Replace(whitespacecolumn, ' ', '') from MyTable
LTRIM, RTRIM will remove spaces in front and rear of column. In 2016 you can use TRIM function as below to trim special characters as well:
SELECT TRIM( '.,! ' FROM '# test .') AS Result;
Output:
# test

T-SQL Substring - Last 3 Characters

Using T-SQL, how would I go about getting the last 3 characters of a varchar column?
So the column text is IDS_ENUM_Change_262147_190 and I need 190
SELECT RIGHT(column, 3)
That's all you need.
You can also do LEFT() in the same way.
Bear in mind if you are using this in a WHERE clause that the RIGHT() can't use any indexes.
You can use either way:
SELECT RIGHT(RTRIM(columnName), 3)
OR
SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)
Because more ways to think about it are always good:
select reverse(substring(reverse(columnName), 1, 3))
declare #newdata varchar(30)
set #newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(#newdata),0,charindex('_',reverse(#newdata))))
=== Explanation ===
I found it easier to read written like this:
SELECT
REVERSE( --4.
SUBSTRING( -- 3.
REVERSE(<field_name>),
0,
CHARINDEX( -- 2.
'<your char of choice>',
REVERSE(<field_name>) -- 1.
)
)
)
FROM
<table_name>
Reverse the text
Look for the first occurrence of a specif char (i.e. first occurrence FROM END of text). Gets the index of this char
Looks at the reversed text again. searches from index 0 to index of your char. This gives the string you are looking for, but in reverse
Reversed the reversed string to give you your desired substring
if you want to specifically find strings which ends with desired characters then this would help you...
select * from tablename where col_name like '%190'