some guidance in modifying the query - sql

I'm using the below query in order to split the value of a column into another column and is working fine, but it is not giving the output that I'm expecting. Below is the query along with the output.
Query:
SELECT
upper(regexp_substr(db_attributes, '[^,:]+$',1,1)) AS servername,
db_attributes FROM
table_name
Current Output:
Servername db_attributes
INPRD1HF hkp04lp0605s-rs6000.hk.hsbc, 50000, AP4INPU1:INPRD1HF
AE000BDS0096\LIVE0096MSSQL ae000bds0096.hbeu.adroot.hsbc, 60695, AE000BDS0096\LIVE0096MSSQL
NULL ora-abacogp.de.hsbc, 1626, ABACOGP
Desired output:
Servername db_attributes
AP4INPU1 hkp04lp0605s-rs6000.hk.hsbc, 50000, AP4INPU1:INPRD1HF
AE000BDS0096\LIVE0096MSSQL ae000bds0096.hbeu.adroot.hsbc, 60695, AE000BDS0096\LIVE0096MSSQL
ABACOGP ora-abacogp.de.hsbc, 1626, ABACOGP
The difference between the current and desired output is in the first line I want the value which is before colon in db_attributes column (i.e. AP4INPU1 not INPRD1HF)
Regards,
Vikas

You may use
regexp_substr(db_attributes, '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1)
Details
([^,:[:space:]]+) - Group 1: one or more chars other than ,, : and whitespace chars
(:\S*)? - an optional group matching 1 or 0 sequences of : and then 0+ non-whitespace chars
$ - end of string.
See the online tests:
--select regexp_substr('hkp04lp0605s-rs6000.hk.hsbc, 50000, AP4INPU1:INPRD1HF', '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1) AS servername from dual
-- => AP4INPU1
--select regexp_substr('ora-abacogp.de.hsbc, 1626, ABACOGP', '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1) AS servername from dual
-- => ABACOGP
--
select regexp_substr('ae000bds0096.hbeu.adroot.hsbc, 60695, AE000BDS0096\LIVE0096MSSQL', '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1) AS servername from dual
-- => AE000BDS0096\LIVE0096MSSQL

Related

Parsing txt file with substring

I inherited a SQL code from my previous co-worker. The script was working the last time I ran it but it returns an error when I tried it today. Surprisingly the code is working on my colleague's PC. I double-check the SQL server database and we are using the same collation, Latin1_General_CS_AS. I did many tests, changing windows system locale etc however none of them work, the error is this:
Msg 207, Level 16, State 1, Line 141
Invalid column name 'Value'.
Msg 207, Level 16, State 1, Line 141
Invalid column name 'Value'.
...
However, I couldn't get it! why it is working on one system and not on another! Does anybody has any idea or alternative solution for the substring part.
DROP TABLE IF EXISTS #VievingLive0
SELECT
ProdDay, -- date
HouseId, -- ID
CAST(SUBSTRING(RowText, 2, CHARINDEX('_', RowText, 2)-2) AS INT) AS ChannelId, -- Channel ID
CASE WHEN LEN(s.Value) = 14 THEN LEFT(s.Value, 2) ELSE STUFF(LEFT(s.Value, LEN(s.Value)-12), 3, 0, '_') END AS Individs, -- list of persons
(LEN(s.Value)-12)/2 AS CntIndiv, -- number of persons watching
DATEADD(SECOND, substring(s.Value,LEN(s.Value)-11,2)*3600+substring(s.Value,LEN(s.Value)-9,2)*60+substring(s.Value,LEN(s.Value)-7,2), CAST(ProdDay AS DATETIME)) AS ViewFrom, -- time from
DATEADD(SECOND, substring(s.Value,LEN(s.Value)-5 ,2)*3600+substring(s.Value,LEN(s.Value)-3,2)*60+substring(s.Value,LEN(s.Value)-1,2)+1, CAST(ProdDay AS DATETIME)) AS ViewTo -- time to
INTO #VievingLive0
FROM #All_TX4_files
CROSS APPLY STRING_SPLIT(SUBSTRING(RowText, PATINDEX('%_[A-Za-z][A-Za-z][A-Za-z0-9]%', SUBSTRING(RowText, 2, LEN(RowText)))+2, LEN(RowText)), '_') AS s -- extracting individual vieiwng statemenets from the row
WHERE LEFT(RowText, 1) = 'V' -- LIVE viewing rows
I am trying to parse this format txt:
H98500410_0
W1941.51
Pab_2467211514110343733611_W2898.81
V100_0_2_210_ab075700080859_ab081100081259_ab081700081959_ab082800083059_ab083400083559_ab110600110959_ab111300111459_ab113500115059_ab115300120259_ab120300120359_ab120400123059_ab123100123559_ab124800125359_ab173200173259_ab191200191359_ab191600191759

split an email list by delimiter returns more than expected number of rows [duplicate]

This question already has answers here:
Connect by in Oracle SQL
(2 answers)
Closed 3 years ago.
I have the following schema and SQL script: http://www.sqlfiddle.com/#!4/9c7bb/9
create table a(
cond varchar2(400),
email varchar2(400)
);
insert into a values('CPU_consumption', 'name_1#email.com;name_2#email.com;name_3#email.com');
insert into a values('number of processes', 'name_1#email.com');
insert into a values('memory consumption', 'name_1#email.com;name_2#email.com;');
SELECT
regexp_substr(email,'((.*?)*?)(;|$)',1,level,NULL,1) AS result
FROM a
WHERE cond = 'memory consumption'
CONNECT BY level < regexp_count(email,'((.*?)*?)(;|$)');
Result:
name_2#email.com
name_2#email.com
name_1#email.com
name_2#email.com
Can anyone explain why the result is not only 2 rows with the email addresses?
Why there is displayed the 2nd email; address twice and after that the required list?
Because connect by mixed memory consumption with other values. You can check it if you add path and root in your query:
select level, regexp_substr(email,'((.*?)*?)(;|$)', 1, level, null, 1) as result,
connect_by_root(cond) root, sys_connect_by_path(cond, ' -> ') path
from a
where cond = 'memory consumption'
connect by level < regexp_count(email,'((.*?)*?)(;|$)');
You should start with proper value and check it in next steps:
select level, regexp_substr(email,'((.*?)*?)(;|$)', 1, level, null, 1) as result
from a
connect by level < regexp_count(email,'((.*?)*?)(;|$)') and cond = 'memory consumption'
start with cond = 'memory consumption';
fiddle

Using variable in Oracle function

I have a variable and want to use in a query inside fuzzy function but it is giving me some syntax error or wrong result considering the var.
ORA-20000: Oracle Text error:
DRG-50901: text query parser syntax error on line 1, column 21 29902.
00000 - "error in executing ODCIIndexStart() routine"
When I replace the my_var variable in the fuzzy function with some static string it works fine but with variable it is giving me this error.
My query is as follows:
DEFINE my_var = 'Bhularam';
SELECT a.EXTERNALID_ENC,
a.EXTERNALID,
a.TELNUMBER,
a.TELAREACODE,
a.DQ_ENGLISH_NAME,
a.DQ_ARABIC_NAME,
a.NAMEFIELD_1,
a.USAGETYPE,
a.MANUAL_UPDATE_FLAG,
a.RULE_UPDATE_FLAG,
a.BUSINESS_UPDATE_FLAG,
a.EXCEL_UPDATE_FLAG
FROM (
SELECT * FROM (
SELECT dqlist.*,
score(1) AS rank
FROM dq_list_hash_full dqlist
WHERE contains(dqlist.dq_english_name
,'definescore(fuzzy(my_var, 1, 6, weight),relevance)',1) > 0
UNION
SELECT
dqlist.*,
score(1) AS rank
FROM
dq_list_hash_full dqlist
WHERE
contains(dqlist.dq_english_name,'!Bhularam',1) > 0
)
ORDER BY
rank DESC
) a
I know it is something really stupid but I am unable to get my head around it probably I am new to oracle. Please help me out.
If using sqlplus, verify what prefix character is used to identify substitution variables. Default is set to '&'.
sqlplus > show define
define "&" (hex 26)
Try using your substitution variable within your query, for example
sqlplus > define my_var='hello world!'
sqlplus > select '&my_var' from dual;
old 1: select '&my_var' from dual
new 1: select 'hello world!' from dual
'HELLOWORLD!'
--------------------------------
hello world!
For your query try (assuming define is set to '&'):
'definescore(fuzzy(&my_var, 1, 6, weight),relevance)',1)

Remove specific character from string (SQL Server 2012)

I have a view from which I want to remove a specific character in one of the columns. Specifically the character 'B' from the 'Fund' column below.
I tried using the following version of TRIM
SELECT
TRIM('B' FROM [Port_Ticker]) as "Fund"
,[BENCH_Ticker] as "Index ID"
,format(cast([VALUE_DATE] as Date),'dd/MM/yyyy') as "Updat"
,([Port_Risk_Contrib] / 10000000) as "StDev Fund"
,([Active_risk_contrib] / 10000000) as "TE"
,([BENCH_RISK_CONTRIB] / 100) as "StDev BM"
FROM [DM_PORTFOLIO_ANALYSIS].[basedata].[PortfolioRiskFigures]
where [BLOCK_FACTOR] = 'Total'
and [Port_ticker] =
'B1023'
order by [VALUE_DATE] asc
Which gives me the error
Msg 156, Level 15, State 1, Line 3.
Incorrect syntax near the keyword 'FROM'.
You can use replace() to do this. In this case it will search for 'B' and replace it with an empty string -> ''. Please note that this function will replace all 'B' from this column.
SELECT
REPLACE([Port_Ticker], 'B', '') as "Fund"
,[BENCH_Ticker] as "Index ID"
,format(cast([VALUE_DATE] as Date),'dd/MM/yyyy') as "Updat"
,([Port_Risk_Contrib] / 10000000) as "StDev Fund"
,([Active_risk_contrib] / 10000000) as "TE"
,([BENCH_RISK_CONTRIB] / 100) as "StDev BM"
FROM [DM_PORTFOLIO_ANALYSIS].[basedata].[PortfolioRiskFigures]
where [BLOCK_FACTOR] = 'Total'
and [Port_ticker] = 'B1023'
order by [VALUE_DATE] asc
The Trim() function was introduced in 2017 version.
Naturally, you can't use it in older versions.
There are several ways this can be done, by using replace as M. Kanarkowski demonstrated in his answer, or any of these options:
stuff: STUFF([Port_Ticker], 1, 1, '') As "Fund",
substring: SUBSTRING([Port_Ticker], 2, LEN([Port_Ticker])) As "Fund"
Right: RIGHT([Port_Ticker], LEN([Port_Ticker])-1) As "Fund"

how Remove certain character at Front and back of a varchar

I have a customer data such as below
Table= Customer
field= CardNo
Data in CardNo:
%ABC?;9991?
%ABC?;99912?
%ABC?;999123?
%ABC?;888123?
Output i want is
9991
99912
999123
888123
However I want to remove all the "%ABC?;" at the front and "?" at the back, in the entire CardNo field. How I do it? I have tried this with no success:
UPDATE Customer
SET cardno = RIGHT(cardno, LEN(cardno) - 7)
I get an error:
"Return Error
Msg 536, Level 16, State 2, Line 1
Invalid length parameter passed to the RIGHT function.
The statement has been terminated."
What's wrong and how can I fix it?
Try like this...
UPDATE Table1 Set Cid=Replace(Left(Cid,Len(CID)-1),'%ABC?;','') FROM TABLE1
Sql Fiddle Demo
If you don't mean exactly this, you should probably be more clear what your intended result is:
DECLARE #foo VARCHAR(32)
SET #foo = '%ABC?;888123?'
SELECT SUBSTRING(#foo, 7, LEN(#foo) - 7)
Result: 888123
As applied to your code:
UPDATE Customer
SET cardno = SUBSTRING(cardno, 7, LEN(cardno) - 7)
Demo
REPLACE will work well. REPLACE('%ABC?;9991?', '%ABC?', '')
You can chain them together to remove the second ? as well.
Here is a rather brute force way, considering all possibilities for the pattern:
UPDATE Customer
SET cardno = (case when cardno like '[%]ABC[?];%[?]'
then substring(cardno, 6, len(cardno) - 7)
when cardno like '[%]ABC[?];%'
then substring(cardno, 6, len(cardno) - 6)
when cardno like '%[?]'
then substring(cardno, len(cardno) - 1)
else cardno
end)