ORA-01427: single-row Subquery Returns More Than One Row for Update - oracle

Hi I am trying to execute but getting error single row subquery returns more than one row.
update upld_mktprice
set (upld_mktprice.orig_security, upld_mktprice.stk_exch, upld_mktprice.stk_group, upld_mktprice.instr_type) =
(select security.security,nvl(upld_mktprice.stk_exch,
nvl(security.stk_exch,'DIRECT')),
security.stk_group,
decode(upld_mktprice.source,'FOREX','X','S') as instr_type -- HLAMUAT-1457146: Passing DIRECT as a default value for HLAM. confirmed by Dheeren/Prasanth.
from v_security_all security
where upld_mktprice.security = Decode(security.asset_type,'OPT',security.stk_sec_id||' '||substr(security.security,instrb(security.security, ' ', 1,1)+3, length(security.security)),security.stk_sec_id)
and rectype = 'L'),
upld_mktprice.currency = nvl(upld_mktprice.currency,''),
upld_mktprice.value_date = nvl(upld_mktprice.value_date,''),
upld_mktprice.amc_code = 'AMC'
Where exists (select 1
from v_security_all security
where upld_mktprice.security = Decode(security.asset_type,'OPT',security.stk_sec_id||' '||substr(security.security,instrb(security.security, ' ', 1,1)+3, length(security.security)),security.stk_sec_id)
and rectype = 'L')
and upld_mktprice.orig_security is null
and upld_mktprice.user_id = 'SRINIVAS'
and upld_mktprice.source = 'MKTPRICEMAN';

I think the error pretty much speaks for itself. The portion of your query below is returning more than one row. There is no way for us to validate because we do not have the data that you have. It might also be a bit easier to troubleshoot if you used table aliases in your update statement.
(SELECT security.security,
NVL (upld_mktprice.stk_exch, NVL (security.stk_exch, 'DIRECT')),
security.stk_group,
DECODE (upld_mktprice.source, 'FOREX', 'X', 'S') AS instr_type -- HLAMUAT-1457146: Passing DIRECT as a default value for HLAM. confirmed by Dheeren/Prasanth.
FROM v_security_all security
WHERE upld_mktprice.security =
DECODE (security.asset_type,
'OPT', security.stk_sec_id
|| ' '
|| SUBSTR (security.security,
INSTRB (security.security,
' ',
1,
1)
+ 3,
LENGTH (security.security)),
security.stk_sec_id)
AND rectype = 'L')

Related

Oracle function to select multiple rows in a single row not working

I am loading a file into a staging record using Application Engine. when ever there is blank in BU,Deptid etc... I have to capture what all columns are blank and update error text field with those values.
UPDATE SYSADM.PS_VI_EMP_TS SET ERR_TEXT =
SELECT ERROR FROM (SELECT * FROM (
SELECT CASE WHEN BUSINESS_UNIT = ' ' THEN 'BUSINESS_UNIT IS NULL' ELSE ' ' END AS ERROR FROM SYSADM.PS_VI_EMP_TS WHERE USERID='JCOOPER' AND ACTION = 'E' AND PROCESS_INSTANCE = '7852429'
UNION
SELECT CASE WHEN DEPTID = ' ' THEN 'DEPTID IS NULL' ELSE ' ' END AS ERROR FROM SYSADM.PS_VI_EMP_TS WHERE USERID='JCOOPER' AND ACTION = 'E' AND PROCESS_INSTANCE = '9852429'
UNION
SELECT CASE WHEN PROJECT_ID =' ' THEN 'PROJECT_ID IS NULL' ELSE ' ' END AS ERROR FROM SYSADM.PS_VI_EMP_TS WHERE USERID='JCOOPER' AND ACTION = 'E' AND PROCESS_INSTANCE = '9852429'
)) WHERE ERROR <> ' '
WHERE USERID='JCOOPER' AND ACTION = 'E' AND PROCESS_INSTANCE = '9852429'
The above script results as below.
ERROR
BUSINESS_UNIT IS NULL
DEPTID IS NULL
I want the result as below.
ERROR
BUSINESS_UNIT IS NULL,DEPTID IS NULL
I am using ListAgg function but facing errors as below.Any help would be great.
SELECT LISTAGG(BUSINESS_UNIT, ';') WITHIN GROUP(ORDER BY USERID)
FROM SYSADM.PS_VI_EMP_TS WHERE USERID='JCOOPER'
GROUP BY BUSINESS_UNIT
Facing the error:
ORA-00923: FROM keyword not found where expected
00923. 00000 - "FROM keyword not found where expected"
*Cause:
*Action:
Error at Line: 47 Column: 43
You overcomplicated things. You don't need two unions and listagg at all. Simple use concatenation of case... when, write your select like here:
select case business_unit when ' ' then 'BUSINESS_UNIT IS NULL; ' end ||
case deptid when ' ' then 'DEPTID IS NULL; ' end ||
case project_id when ' ' then 'PROJECT_ID IS NULL; ' end as error
from ps_vi_emp_ts
where userid = 'JCOOPER' and action = 'E' and process_instance = '9852429'
demo
If your table has primary key then use it for update. Otherwise you can use merge with rowid. Or do it the way you did it if it worked for you, especially if there is only one row meeting criteria.

Re-writing Query

Overall Task :- I need to retrieve data from 45 fields in system A and dump that data into a temp table which is then picked up by a unix process which produces an xml data file to be imported into system B.
Specific Question : What would be the best way of retrieving the data to be written into the 45 fields. Majority of the data is independent and can't be retrieved using a single statement. The way i currently retrieve this data is as follows (example below)
My temp tables hold the affected properties ID that i need to extract data for. i.e PROP_LIST_TEMP and ASSOC_PROP_TEMP.
SELECT SUBSTR (pro.pro_propref, 1, 25) UPRN,
(SELECT SUBSTR (adr_building, 1, 100)
FROM addresses, address_usages
WHERE aus_adr_refno = adr_refno
AND aus_aut_far_code = 'PHYSICAL'
AND aus_aut_fao_code = 'PRO'
AND (aus_end_date IS NULL OR aus_end_date > SYSDATE)
AND aus_pro_refno = pro.pro_refno)
BUILDING_NAME,
(SELECT CASE
WHEN (adr_street_number like 'BLOC%'
OR adr_street_number like '%-%'
OR adr_street_number like '%/%')
THEN NULL
ELSE regexp_replace (adr_street_number, '[^[:digit:]]+')
END
FROM addresses, address_usages
WHERE aus_adr_refno = adr_refno
AND aus_aut_far_code = 'PHYSICAL'
AND aus_aut_fao_code = 'PRO'
AND (aus_end_date IS NULL OR aus_end_date > SYSDATE)
AND aus_pro_refno = pro.pro_refno)
STREET_NUMBER,
(SELECT CASE
WHEN (adr_street_number like 'BLOC%'
OR adr_street_number like '%-%'
OR adr_street_number like '%/%')
THEN SUBSTR (adr_street_number, 1, 20)
ELSE REGEXP_REPLACE (adr_street_number, '[^[:alpha:]]+', '')
END
FROM addresses, address_usages
WHERE aus_adr_refno = adr_refno
AND aus_aut_far_code = 'PHYSICAL'
AND aus_aut_fao_code = 'PRO'
AND (aus_end_date IS NULL OR aus_end_date > SYSDATE)
AND aus_pro_refno = pro.pro_refno)
STREET_NUMBER_SUFFIX,
(SELECT SUBSTR (ptv_pty_code, 1, 3)
FROM prop_type_values
WHERE ptv_refno = pro.pro_hou_ptv_refno)
HOUSE_TYPE
FROM properties pro
WHERE pro_refno IN (select * from PIMSS_PROP_LIST_TEMP
UNION
select * from PIMSS_ASSOC_PROP_TEMP)
AND pro.pro_hou_hrv_hot_code IN
(SELECT frv_code
FROM first_ref_values
WHERE frv_frd_domain IN ('ASS_OWN_REF')
AND frv_current_ind = 'Y');
Since the where clauses of the subqueries in the select statement are identical, you could simply pull that out into the where clause, like so:
SELECT SUBSTR (pro.pro_propref, 1, 25) UPRN,
SUBSTR (addr.adr_building, 1, 100) BUILDING_NAME,
CASE WHEN (addr.adr_street_number like 'BLOC%'
OR addr.adr_street_number like '%-%'
OR addr.adr_street_number like '%/%')
THEN NULL
ELSE regexp_replace (addr.adr_street_number, '[^[:digit:]]+')
END STREET_NUMBER,
CASE WHEN (addr.adr_street_number like 'BLOC%'
OR addr.adr_street_number like '%-%'
OR addr.adr_street_number like '%/%')
THEN SUBSTR (addr.adr_street_number, 1, 20)
ELSE REGEXP_REPLACE (addr.adr_street_number, '[^[:alpha:]]+', '')
END STREET_NUMBER_SUFFIX,
(SELECT SUBSTR (ptv_pty_code, 1, 3)
FROM prop_type_values
WHERE ptv_refno = pro.pro_hou_ptv_refno) HOUSE_TYPE
FROM properties pro,
(select adr_building,
adr_street_number
FROM addresses, address_usages
WHERE aus_adr_refno = adr_refno
AND aus_aut_far_code = 'PHYSICAL'
AND aus_aut_fao_code = 'PRO'
AND (aus_end_date IS NULL OR aus_end_date > SYSDATE)) addr
WHERE pro.pro_refno = aus_pro_refno
and pro_refno IN (select * from PIMSS_PROP_LIST_TEMP
UNION
select * from PIMSS_ASSOC_PROP_TEMP)
AND pro.pro_hou_hrv_hot_code IN (SELECT frv_code
FROM first_ref_values
WHERE frv_frd_domain IN ('ASS_OWN_REF')
AND frv_current_ind = 'Y');
You might possibly need an outer join if there's a chance that no rows could be returned from the addr subquery.

Join condition in Oracle query

I have following query which update the coulmn "tmp_activation_date" of rec_tmprecord table with max of actdate according to the conditions mentioned in query.
MERGE INTO rec_tmprecord
USING (SELECT rec.ID, MAX (act.actdate) AS tmpactivation_date
FROM rec_tmprecord rec INNER JOIN tmp_asset asset
ON asset.serial = rec.serialtemp
and upper (replace (asset.prodname, 'Ajink ')) = upper (replace (rec.prodnametemp, 'Ajink '))
and NVL(asset.release,'NF') = NVL(rec.tmprelease ,'NF')
and rec.serialtemp != 'aaa-aaaaaaaa'
LEFT JOIN tmp_acti_hist act
ON asset.tmp_id = act.tmp_row_id
WHERE rec.cust_id = 234567
GROUP BY rec.cust_id,asset.serial,rec.ID) new_values
ON (rec_tmprecord.ID = new_values.ID)
WHEN MATCHED THEN
UPDATE
SET tmp_activation_date = new_values.tmpactivation_date
;
But,When i analyzed the data of table "rec_tmprecord",i found that there are some null or blank values present in the "prodnametemp" column of "rec_tmprecord" table.But,column "prodname" of the table "tmp_asset" does not contain any null or blank values.
So,my join condition will fail at "upper (replace (asset.prodname, 'Ajink ')) = upper (replace (rec.prodnametemp, 'Ajink '))" condition and as a result "tmp_activation_date" of rec_tmprecord table will be updated with null value or blank value.
what my requirement is if "prodnametemp" is having null value and "prodname" contains some value then also "tmpactivation_date" will get calculated on the basis of other conditions mentioned in the query.
Anyhelp on this would be greatly appreciated.
Here is a modified version. I modified the join as follows:
upper (replace (asset.prodname, 'Ajink ')) = NVL(upper (replace (rec.prodnametemp, 'Ajink ')), upper (replace (asset.prodname, 'Ajink ')))
EDIT:
The join condition has been compressed, thanks to Alex Poole's suggestion.
Basically, if is NULL, then that condition would return TRUE, because then asset.prodname = asset.prodname.
MERGE INTO rec_tmprecord
USING (SELECT rec.ID, MAX (act.actdate) AS tmpactivation_date
FROM rec_tmprecord rec INNER JOIN tmp_asset asset
ON asset.serial = rec.serialtemp
and upper (replace (asset.prodname, 'Ajink ')) = upper (replace (NVL (rec.prodnametemp, asset.prodname), 'Ajink '))
and NVL(asset.release,'NF') = NVL(rec.tmprelease ,'NF')
and rec.serialtemp != 'aaa-aaaaaaaa'
LEFT JOIN tmp_acti_hist act
ON asset.tmp_id = act.tmp_row_id
WHERE rec.cust_id = 234567
GROUP BY rec.cust_id,asset.serial,rec.ID) new_values
ON (rec_tmprecord.ID = new_values.ID)
WHEN MATCHED THEN
UPDATE
SET tmp_activation_date = new_values.tmpactivation_date
;

What is the right Update Statement in Oracle 11g

My original update statement is still working great in Sybase (see below) but we're migrating to Oracle 11g and I have to convert this update statement into Oracle Update.
I tried so many version and keep getting error, I guess I have not gotten a grib of how Oracle Update statement works. Can anyone help?
My original good Update Statement (in Sybase):
UPDATE Valid
SET A.status = 'X',
A.reason = 'Missing'
FROM Valid A, Valid B
WHERE A.id_number = B.id_number
AND A.session_id = 69
AND A.userid = 'BS'
AND A.status = 'A'
AND isnull(B.street1, ' ') = ' '
Below is my Oracle version that is not working no matter what I did:
MERGE
INTO um_valid Target
USING (select * from um_valid) SOURCE
ON (t1.id_number = t2.id_number)
WHEN MATCHED THEN
UPDATE
SET status = 'X',
reason = 'Missing (street 1)'
WHERE Target.session_id = 69
AND Target.userid = 'BS'
AND Target.status = 'A'
AND NVL(SOURCE.street1, ' ') = ' ')
The error I'm getting:
ORA-00933: SQL command not properly ended
The WHERE clause at the end isn't appropriate. Maybe you need this:
MERGE
INTO um_valid Target
USING (
select distinct id_number
from um_valid
where street1 is null
) SOURCE
ON (
Target.id_number = SOURCE.id_number
AND Target.session_id = 69
AND Target.userid = 'BS'
AND Target.status = 'A'
)
WHEN MATCHED THEN UPDATE SET
status = 'X',
reason = 'Missing (street 1)'
You can use a normal update statement. Merge is for bulk operations.
If you need to update something when it exists or insert when it doesn't then you can use a merge statement.
So for your example try using the following:
UPDATE Valid
SET status = 'X',
reason = 'Missing'
WHERE session_id = 69
AND userid = 'BS'
AND status = 'A'
AND street1 is null
The above statement will update all rows in table "Valid" where session_id equals 69, userid equals BS, status equals A and street1 is empty (null).
I think this is what you need, if this is not the case pls let me know why you join valid with valid. The I will adjust my update.
This ought to do it:
UPDATE Valid a
SET status = 'X',
reason = 'Missing'
WHERE A.session_id = 69
AND A.userid = 'BS'
AND A.status = 'A'
AND exists (select null
from valid b
where a.id_number = b.id_number
AND coalesce(B.street1, ' ') = ' ')

How to return all rows if IN clause has no value?

Following is sample query.
CREATE PROCEDURE GetModel
(
#brandids varchar(100), -- brandid="1,2,3"
#bodystyleid varchar(100) -- bodystyleid="1,2,3"
)
AS
select * from model
where brandid in (#brandids) -- use a UDF to return table for comma delimited string
and bodystyleid in (#bodystyleid)
My requirement is that if #brandids or #bodystyleid is blank, query should return all rows for that condition.
Please guide me how to do this? Also suggest how to write this query to optimize performance.
You'll need dynamic SQL or a split function for this anyway, since IN ('1,2,3') is not the same as IN (1,2,3).
Split function:
CREATE FUNCTION dbo.SplitInts
(
#List VARCHAR(MAX),
#Delimiter CHAR(1)
)
RETURNS TABLE
AS
RETURN ( SELECT Item = CONVERT(INT, Item) FROM (
SELECT Item = x.i.value('(./text())[1]', 'int') FROM (
SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(#List, #Delimiter, '</i><i>')
+ '</i>').query('.') ) AS a CROSS APPLY [XML].nodes('i') AS x(i)) AS y
WHERE Item IS NOT NULL
);
Code becomes something like:
SELECT m.col1, m.col2 FROM dbo.model AS m
LEFT OUTER JOIN dbo.SplitInts(NULLIF(#brandids, ''), ',') AS br
ON m.brandid = COALESCE(br.Item, m.brandid)
LEFT OUTER JOIN dbo.SplitInts(NULLIF(#bodystyleid, ''), ',') AS bs
ON m.bodystyleid = COALESCE(bs.Item, m.bodystyleid)
WHERE (NULLIF(#brandids, '') IS NULL OR br.Item IS NOT NULL)
AND (NULLIF(#bodystyleid, '') IS NULL OR bs.Item IS NOT NULL);
(Note that I added a lot of NULLIF handling here... if these parameters don't have a value, you should be passing NULL, not "blank".)
Dynamic SQL, which will have much less chance of leading to bad plans due to parameter sniffing, would be:
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'SELECT columns FROM dbo.model
WHERE 1 = 1 '
+ COALESCE(' AND brandid IN (' + #brandids + ')', '')
+ COALESCE(' AND bodystyleid IN (' + #bodystyleid + ')', '');
EXEC sp_executesql #sql;
Of course as #JamieCee points out, dynamic SQL could be vulnerable to injection, as you'll discover if you search for dynamic SQL anywhere. So if you don't trust your input, you'll want to guard against potential injection attacks. Just like you would if you were assembling ad hoc SQL inside your application code.
When you move to SQL Server 2008 or better, you should look at table-valued parameters (example here).
if(#brandids = '' or #brandids is null)
Begin
Set #brandids = 'brandid'
End
if(#bodystyleid = '' or #bodystyleid is null)
Begin
Set #bodystyleid = 'bodystyleid'
End
Exec('select * from model where brandid in (' + #brandids + ')
and bodystyleid in (' + #bodystyleid + ')')

Resources