Replace part of string in table column - sql

Using Remove part of string in table as an example, I want to change part of my string in my database column with a different string.
Ex:
Database says E:\websites\nas\globe.png , E:\websites\nas\apple.png and etc
I want it to say \\nas\globe.png, \\nas\apple.png,
Only part I want to replace is the E:\websites\ not the rest of the string
How do I do this?
So far I have:
SELECT file_name,
REPLACE(file_name,'E:\websites\','\\nas\')
FROM t_class;
I just referenced http://nntp-archive.sybase.com/nntp-archive/action/article/%3C348_1744DC78C1045E920059DE7F85256A8B.0037D71C85256A8B#webforums%3E
and used:
SELECT REPLACE('E:\websites\web\Class\Main_Image\','E:\websites\web\Class\Main_Image\','\\nas\class_s\Main_Image\') "Changes"
FROM DUAL;
but once again it wouldn't change O.o

In Oracle, you may need to double up on the back slashes:
SELECT file_name,
REPLACE(file_name,'E:\\websites\\', '\\\\nas\\')
FROM t_class;

For the fun of it, using regexp_replace:
SQL> with tbl(filename) as (
2 select 'E:\websites\nas\globe.png' from dual
3 union
4 select 'E:\websites\nas\apple.png' from dual
5 )
6 select filename, regexp_replace(filename, 'E:\\websites', '\\') edited
7 from tbl;
FILENAME EDITED
------------------------- --------------------
E:\websites\nas\apple.png \\nas\apple.png
E:\websites\nas\globe.png \\nas\globe.png
SQL>

I found a reference at how to replace string values of column values by SQL Stored Procedure
by doing the following:
UPDATE t_class SET file_name =
REPLACE
(file_name, 'E:\websites\web\Class\Main_Image\No_Image_Available.png', '\\nas\class_s\Main_Image\No_Image_Available.png');
so only difference is the update and = sign

Related

ORACLE TO_CHAR SPECIFY OUTPUT DATA TYPE

I have column with data such as '123456789012'
I want to divide each of each 3 chars from the data with a '/' in between so that the output will be like: "123/456/789/012"
I tried "SELECT TO_CHAR(DATA, '999/999/999/999') FROM TABLE 1" but it does not print out the output as what I wanted. Previously I did "SELECT TO_CHAR(DATA, '$999,999,999,999.99') FROM TABLE 1 and it printed out as "$123,456,789,012.00" so I thought I could do the same for other case as well, but I guess that's not the case.
There is also a case where I also want to put '#' in front of the data so the output will be something like this: #12345678901234. Can I use TO_CHAR for this problem too?
Is these possible? Because when I go through the documentation of oracle about TO_CHAR, it stated a few format that can be use for TO_CHAR function and the format that I want is not listed there.
Thank you in advance. :D
Here is one option with varchar2 datatype:
with test as (
select '123456789012' a from dual
)
select listagg(substr(a,(level-1)*3+1,3),'/') within group (order by rownum) num
from test
connect by level <=length(a)
or
with test as (
select '123456789012.23' a from dual
)
select '$'||listagg(substr((regexp_substr(a,'[0-9]{1,}')),(level-1)*3+1,3),',') within group (order by rownum)||regexp_substr(a,'[.][0-9]{1,}') num
from test
connect by level <=length(a)
output:
1st query
123/456/789/012
2nd query
$123,456,789,012.23
If you wants groups of three then you can use the group separator G, and specify the character to use:
SELECT TO_CHAR(DATA, 'FM999G999G999G999', 'NLS_NUMERIC_CHARACTERS=./') FROM TABLE_1
123/456/789/012
If you want a leading # then you can use the currency indicator L, and again specify the character to use:
SELECT TO_CHAR(DATA, 'FML999999999999', 'NLS_CURRENCY=#') FROM TABLE_1
#123456789012
Or combine both:
SELECT TO_CHAR(DATA, 'FML999G999G999G999', 'NLS_CURRENCY=# NLS_NUMERIC_CHARACTERS=./') FROM TABLE_1
#123/456/789/012
db<>fiddle
The data type is always a string; only the format changes.

Capturing particular part of Integer Value from part of a String value

I have a table like cust_attbr consists column attbr which has values like:
{"SRCTAXAMT":"11300",เอ็ก10110","TAXAMT":"11300","LOGID":"190301863","VAT_NUMBER":"0835546003122"}
{"SRCTAXAMT":"11300", กรุงค10110","TAXAMT":"11300","LOGID":"190301863","VAT_NUMBER":"0835546003122"}
........ ... ...
{"SRCTAXAMT":"11300", กรุงค10110","TAXAMT":"11300","LOGID":"190301863","VAT_NUMBER":" "}
So, I have to write one select statement which will fetch only VAT_NUMBER value like:
0835546003122
0835546003122
.... ... ..
null
With sample data you posted:
SQL> select * From test;
ID ATTBR
---------- ----------------------------------------------------------------------------------------------------------------
1 "{"SRCTAXAMT":"11300",????10110","TAXAMT":"11300","LOGID":"190301863","VAT_NUMBER":"0835546003122"}"
2 "{"SRCTAXAMT":"11300", ?????10110","TAXAMT":"11300","LOGID":"190301863","VAT_NUMBER":"0835546003122"}"
3 "{"SRCTAXAMT":"11300", ?????10110","TAXAMT":"11300","LOGID":"190301863","VAT_NUMBER":" "}"
this might be one option:
SQL> select id,
2 regexp_substr(regexp_substr(attbr, 'VAT_NUMBER":"(\d+)?'), '\d+$') vat
3 from test;
ID VAT
---------- --------------------
1 0835546003122
2 0835546003122
3
SQL>
Inner regexp_substr returns VAT_NUMBER followed by optional number, while the outer one extracts only the number anchored to the end of the previous substring.
If you're on 18c and the data is actual json (it currently is not because of the double quotes around the curly braces and the ",.กรุงค10110" - It is unclear that this is because of your sample data) you could use json_table function:
WITH t (json_val) AS
(
SELECT '{"SRCTAXAMT":"11300","TAXAMT":"11300","LOGID":"190301863","VAT_NUMBER":"0835546003122"}' FROM DUAL UNION ALL
SELECT '{"SRCTAXAMT":"11300","TAXAMT":"11300","LOGID":"190301863","VAT_NUMBER":"0835546003122"}' FROM DUAL UNION ALL
SELECT '{"SRCTAXAMT":"11300","TAXAMT":"11300","LOGID":"190301863","VAT_NUMBER":" "}' FROM DUAL
)
SELECT jt.*
FROM t,
JSON_TABLE(json_val, '$'
COLUMNS (first_name VARCHAR2(50 CHAR) PATH '$."VAT_NUMBER"')) jt;
0835546003122
0835546003122
One option would be converting those column values to JSON syntax an then extract the values of VAT_NUMBER keys provided DB version is 12c Release 1+. Here, we have an issue that there are unrecognized characters, probably an alphabet from far east and those strings are not properly quoted, then we need to remove the part upto TAXAMT key, and then extracting VAT_NUMBER key's value through prefixing an opening curly brace('{') by use of JSON_VALUE() function :
SELECT JSON_VALUE(
'{'||REGEXP_REPLACE(str,'(.*10110",)(.*)','\2'),
'$.VAT_NUMBER'
) AS VAT_NUMBER
FROM tab --> your original data source
Demo

Escaping single quotes in REDSHIFT SQL

I've lots of string values containing single quotes which I need to insert to a column in REDSHIFT table.
I used both /' and '' to escape the single quote in INSERT statement.
e.g.
INSERT INTO table_Temp
VALUES ('1234', 'O\'Niel'), ('3456', 'O\'Brien')
I also used '' instead of \' but it keeps giving me error that "VALUES list must of same length" i.e. no: of arguments for each record >2.
Can you let know how to have this issue resolved?
The standard in SQL is double single quotes:
INSERT INTO table_Temp (col1, col2) -- include the column names
VALUES ('1234', 'O''Niel'), ('3456', 'O''Brien');
You should also include the column names corresponding to the values being inserted. That is probably the cause of your second error.
You could use CHR(39) and concat the strings. Your name would look like below:
('O' || CHR(39)||'Brian')
I think it may depend on your environment. I'm using Periscope Data's redshift SQL editor, and \ worked as an escape character. '' and \\ did not work.
I was facing similar problem , I was needing send a kind of JSON structure to then decode it into my query but there was a program receiving my string and this program was escaping my escapes, so the query fails, finally I found this :
Put $$ in dollar-quoted string in PostgreSQL
mentioning quote_literal(42.5)
https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER
This resolves my issue . an example
String is
'LocalTime={US/Central}; NumDays={1}; NumRows={3}; F_ID={[Apple, Orange, Bannana]}'
Select
Param, value , replace(quote_literal(replace(replace(Value,'[',''),']','')),',',quote_literal(',')) ValueList
FROM (
select
SPLIT_PART(split,'=',1) as Param,
replace( replace(SPLIT_PART(split,'=',2),'{',''),'}','') as Value
FROM
(
select
trim(split_part(freeform.txt, ';', number.n)) as split
from
( select
'LocalTime={US/Central}; NumDays={1}; NumRows={3}; F_ID={[Apple, Orange, Bannana]}' as txt
) freeform,
( select 1 as n union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9 union all
select 10
) number
where split <> ''
) as MY_TMP
) as valuePart
use \\' to escape '
s = s.replace("'", "\\'")

How to check the last two digits?

SUBBIS
SUBB1D
SUBBD3
SUBB12
In above values, how can I check the last two digits (IS, 1D, D3, 12) are numbers using a sql code?
Do you mean to fetch those values? You can do that with like:
where column like '%[0-9][0-9]'
If you need to ensure that the values always end with 2 numbers, you can do it with similar check constraint.
To check the last two digits are numbers in column, you can use the following script.
... WHERE ISNUMERIC(RIGHT(your_column,2)) = 1
Here RIGHT(your_column,2) will return the last two digits from the string.
or
SELECT ISNUMERIC(RIGHT(your_column,2))
will return 1 (if its number) otherwise 0
You can do it this way:
SELECT MyId,
ISNUMERIC(RIGHT(MyColumn,2)) -- your column to check last 2 (if numeric)
FROM (
----- replace with your table
SELECT 1 MyId,'SUBBIS' MyColumn UNION SELECT 2,'SUBB1D' UNION
SELECT 3,'SUBBD3' UNION SELECT 4,'SUBB12'
----- replace with your table
) A
Hope it helps. :)
You can use like and _ "underscore" to get last one digits record columName
SELECT columName FROM sub WHERE columName LIKE "SUBB__" ;
Record :
columName
SUBBIS
SUBB1D
SUBBD3
SUBB12
SUBBBA

PLSQL Getting values from string

I have this varchar2(2000) string:
id=100\nid2=0\nid3=0\dtext='more Text'
and I want to get only the values e.g. more Text or 0 (id3).
I was trying to use a customized SPLIT function, where separator is \n but this only returns me for example id3=0 (in this case I need '0' as result).
How can I do this more efficient?
and I want to get only the values e.g. more Text.
Simply use SUBSTR and INSTR
SQL> WITH DATA AS
2 ( SELECT q'[id=100\nid2=0\nid3=0\dtext='more Text']' str FROM dual
3 )
4 SELECT SUBSTR(str,instr(str, '''')+1,LENGTH(SUBSTR(str,instr(str, '''')))-2) str
5 FROM DATA
6 /
STR
---------
more Text
SQL>
You could get all the values with something like this:
WITH DATA AS
(SELECT q'[id=100\nid2=0\nid3=0\ndtext='more Text']' str FROM dual)
SELECT replace(substr(regexp_substr(str,'(=.+?\n)|(=.+?$)',1,level),2),'\n') v
FROM DATA
CONNECT BY LEVEL <= LENGTH(regexp_replace(str,'([^=]+=.+?\n)|([^=]=.+?$)'))