Oracle SQL Update statement with value generated in subquery - sql

I am trying to write an update statement to insert a value that's calculated in a subquery, and having limited success.
The statement I've tried so far is:
update intuit.men_doc doc1
set doc1.doc_udf5 = (select
substr(doc.doc_dtyc, instr(doc.doc_dtyc, 'GAPP-', 2)+5 )||'_'||row_number() over(partition by
doc.doc_dtyc order by doc.doc_cret) docDeleteId
from
intuit.men_doc doc
where
doc.doc_dtyc != 'DM-GAPP-SFUL'
and doc.doc_dtyc like 'DM-GAPP%'
and doc.doc_cred >= '01/Oct/2017' and doc.doc_cred < '01/Oct/2018'
and doc1.doc_code = doc.doc_code
)
Which gives mes the following error message
ERROR: Error 1427 was encountered whilst running the SQL command. (-3)
Error -3 running SQL : ORA-01427: single-row subquery returns more than one row
I don't have much experience with UPDATE statements, so any advice on how I can rewrite this so that I can update a few thousand records at once would be appreciated.
EDIT: Adding example data
Example data:
MEN_DOC
DOC_CODE DOC_DTYC DOC_UDF5 DOC_CRED
123456A CV 08/Nov/2017
456789B CV 11/Jan/2018
789123C CV 15/Feb/2018
123987B TRAN 01/Dec/2017
How I want the data to look once the script is run
MEN_DOC
DOC_CODE DOC_DTYC DOC_UDF5 DOC_CRED
123456A CV CV_1 08/Nov/2017
456789B CV CV_2 11/Jan/2018
789123C CV CV_3 15/Feb/2018
123987B TRAN TRAN_1 01/Dec/2017
Thanks

You are using row_number(), which suggests that you expect the subquery to return more than one row. The inequality on doc_code supports this interpretation.
Just change the row_number() to count(*), so you have an aggregation which will always return one row and get the sequential count you want:
update intuit.men_doc doc1
set doc1.doc_udf5 = (select substr(doc.doc_dtyc, instr(doc.doc_dtyc, 'GAPP-', 2)+5 ) ||'_'|| count(*) docDeleteId
from intuit.men_doc doc
where doc.doc_dtyc <> 'DM-GAPP-SFUL' and
doc.doc_dtyc like 'DM-GAPP%' and
doc.doc_cred >= date '2017-10-01' and
doc.doc_cred < date '2018-10-01' and
doc1.doc_code = doc.doc_code
);

You can use your select as source table in merge, like here:
merge into men_doc tgt
using (select doc_code,
doc_dtyc||'_'||row_number() over (partition by doc_dtyc order by doc_cred) as calc
from men_doc) src
on (tgt.doc_code = src.doc_code)
when matched then update set tgt.doc_udf5 = src.calc;
dbfiddle
I assumed that doc_code is unique.

Related

Oracle SQL update statement how to update two rows at a time

I tried to update two rows in a table.
If I used:
update ERNTESTUPDATE a
set (date_loaded, acad_career) = (select distinct b.date_loaded, b.acad_career
from PS_STDNT_ENRL b
where rownum=1)
where to_char(date_created) = to_char(trunc(sysdate))
;
I got 2 rows updated as
11/29/18 UGRD
11/29/18 UGRD
If I used:
update ERNTESTUPDATE a
set (date_loaded, acad_career) = (select distinct b.date_loaded, b.acad_career
from PS_STDNT_ENRL b
where a.date_loaded = b.date_loaded )
where to_char(date_created) = to_char(trunc(sysdate))
;
I got an error
single-row subquery returns more than one row
How to get a result as below:
11/29/18 UGRD
11/29/18 GRAD
Thank you,
Kate
The subquery needs to return a SINGLE row. That works well when you include the condition rownum=1 in the first one:
select distinct b.date_loaded, b.acad_career
from PS_STDNT_ENRL b
where rownum=1 -- this filter makes sure only one row is returned
If you remove that condition, then the subquery will return multiple rows, and that makes the whole UPDATE fail.

SQL Update when not in subquery?

I have 2 tables:
tblAbsence
Name Start End Status
John 4/2/18 4/5/18 Approved
Sue 5/1/18 5/10/18 Denied
tblManning
Date Required
4/1/18 3
4/2/18 4
4/3/18 2
I would like to be able to update tblAbsence.Status to "Approved" as long as the Required value during the absence request doesn't exceed an arbitrary limit (4 for example).
After looking at #Jeffrey's proposal and experimenting I think I need an Update query which Sets [Status]= Approved when leave request is not found in query below. The below query will tell me if a request has any days that exceed the Limit.
SELECT tblAbsence.name, tblAbsence.start, tblAbsence.end
FROM tblAbsence, tblManning
WHERE tblManning.Date >= Int([tblAbsence].[Start]) And tblManning.Date <= [tblAbsence].[End] AND tblManning.[Req]>3
GROUP BY tblAbsence.name, tblAbsence.[Start], tblAbsence.end;
I renamed the above query as qryLv and tried this Left Join but it tells me I must use an updatable query????
Update tblAbsence a
Left Join qryLv L
ON L.name = a.name AND l.start = a.start
SET a.Status = "Approved"
WHERE l.name is null;
Your error is showing because you have to either equate or use IN/EXISTS with a variable when using subqueries in WHERE clauses. However, I'm not sure you need a subquery, I think something like this will work:
UPDATE tblAbsence SET tblAbsence.Status = "Approved"
FROM tblAbsence, tblManning
WHERE tblManning.Date > tblAbsence.Start
AND tblManning.Date <= tblAbsence.End + #23:59:59#
AND tblManning.Required < 4;
Ok, kinda missed that part, you will need a subquery. I think you need to use NOT EXISTS just to check if your subquery returns any values or not and that should work for you.
UPDATE tblAbsence SET tblAbsence.Status = "Approved"
FROM tblAbsence
WHERE NOT EXISTS (
SELECT NULL
FROM tblManning
WHERE tblManning.Date > tblAbsence.Start
AND tblManning.Date <= tblAbsence.End + #23:59:59#
AND tblManning.Required < 4);
I think you can use NULL in the subquery since you are not returning records, just a boolean, but if it doesn't work you can replace it with *.

Assistance with SQL Query (aggregating)

I have a requirement to create a Sales report and I have a sql query:
SELECT --top 1
t.branch_no as TBranchNo,
t.workstation_no as TWorkstation,
t.tender_ref_no as TSaleRefNo,
t.tender_line_no as TLineNo,
t.tender_code as TCode,
T.contribution as TContribution,
l.sale_line_no as SaleLineNo
FROM TENDER_LINES t
LEFT JOIN SALES_TX_LINES l
on t.branch_no = l.branch_no and t.workstation_no = l.workstation_no and t.tender_ref_no = l.sale_tx_no
where l.sale_tx_no = 2000293 OR l.sale_tx_no = 1005246 --OR sale_tx_no = 1005261
order by t.tender_ref_no asc,
l.sale_line_no desc
The results of the query look like the following:
The results I am trying to achieve is:
With only 1 line for transaction 2 either SaleLineNo 1 or 2, while still have=ing both lines for transaction 1 because the TCode is different.
Thanks
I am using SSQL2012.
Not exactly sure on what data you have, but you might want to try
GROUP BY TlineNo, TCode ...
But you have to keep a look on not to group by something that would result in duplicate contribution values.
You can use the ROW_NUMBER function that allows to partition the rows in groups, and number the lines inside each group starting by one. If you choose the right columns to define the partition, and keep only the rows with "row_number = 1`, you have solved the first part of your problem, i.e. discarding the lines that don't have to appear in the report. (See the sample sin the linked documentation, they're quite clear).
Once you have solved this problem, you simply have to repeat what you're doing, but on the result of this data, instead of the original data. You can use a view, a CTE, or a subselect to achieve your result, i.e.
With view:
CREATE VIEW FilteredData AS -- here the rank function query, then selct from the view
SELECT --here your current query --
FROM FilteredData
With CTE
WITH -- here the rank function query
SELECT -- your current querym, from the CTE
With subselect
SELECT -- your current query
FROM (SELECT FROM -- here the rank function query -- )
Appreciate your assistance with my query. After playing around, I have found a solution that works just as I want. It is as below: I did a Group by as hinted by #Yogesh86 on a few fields.
SELECT
MAX(t.branch_no) as TBranchNo,
Max(t.workstation_no) as TWorkstation,
t.tender_ref_no as TSaleRefNo,
Max(t.tender_line_no) as TLineNo,
t.tender_code as TCode,
MAx(T.contribution) as TContribution,
MAX(l.sale_line_no) as SaleLineNo
FROM TENDER_LINES t
LEFT JOIN SALES_TX_LINES l
on t.branch_no = l.branch_no and t.workstation_no = l.workstation_no and t.tender_ref_no = l.sale_tx_no
where l.sale_tx_no = 2000293 OR l.sale_tx_no = 1005246 --OR sale_tx_no = 1005261
GROUP BY
t.tender_ref_no,
t.tender_line_no,
t.tender_code

single-row subquery returns more than one row. Query not working with main query

I hve to display several cell values into one cell. So I am using this query:
select LISTAGG(fc.DESCRIPTION, ';'||chr(10))WITHIN GROUP (ORDER BY fc.SWITCH_NAME) AS DESCRIP from "ORS".SWITCH_OPERATIONS fc
group by fc.SWITCH_NAME
It is working fine. But when I am merging this with my main(complete) query then I am getting the error as: Error code 1427, SQL state 21000: ORA-01427: single-row subquery returns more than one row
Here is my complete query:
SELECT
TRACK_EVENT.LOCATION,
TRACK_EVENT.ELEMENT_NAME,
(select COUNT(*) from ORS.TRACK_EVENT b where (b.ELEMENT_NAME = sw.SWITCH_NAME)AND (b.ELEMENT_TYPE = 'SWITCH')AND (b.EVENT_TYPE = 'I')AND (b.ELEMENT_STATE = 'NORMAL' OR b.ELEMENT_STATE = 'REVERSE'))as COUNTER,
(select COUNT(*) from ORS.SWITCH_OPERATIONS fc where TRACK_EVENT.ELEMENT_NAME = fc.SWITCH_NAME and fc.NO_CORRESPONDENCE = 1 )as FAIL_COUNT,
(select MAX(cw.COMMAND_TIME) from ORS.SWITCH_OPERATIONS cw where ((TRACK_EVENT.ELEMENT_NAME = cw.SWITCH_NAME) and (cw.NO_CORRESPONDENCE = 1)) group by cw.SWITCH_NAME ) as FAILURE_DATE,
(select LISTAGG(fc.DESCRIPTION, ';'||chr(10))WITHIN GROUP (ORDER BY fc.SWITCH_NAME) AS DESCRIP from "ORS".SWITCH_OPERATIONS fc
group by fc.SWITCH_NAME)
FROM
ORS.SWITCH_OPERATIONS sw,
ORS.TRACK_EVENT TRACK_EVENT
WHERE
sw.SEQUENCE_ID = TRACK_EVENT.SEQUENCE_ID
Not only are subqueries in the SELECT list required to return exactly one row (or any time they're used for a singular comparison, like <, =, etc), but their use in that context tends to make the database execute them RBAR - Row-by-agonizing-row. That is, they're slower and consume more resources than they should.
Generally, unless the result set outside the subquery contains only a few rows, you want to construct subqueries as part of a table-reference. Ie, something like:
SELECT m.n, m.z, aliasForSomeTable.a, aliasForSomeTabe.bSum
FROM mainTable m
JOIN (SELECT a, SUM(b) AS bSum
FROM someTable
GROUP BY a) aliasForSomeTable
ON aliasForSomeTable.a = m.a
This benefits you in other ways to - it's easier to get multiple columns out of the same table-reference, for example.
Assuming that LISTAGG(...) can be included with other aggregate functions, you can change your query to look like this:
SELECT Track_Event.location, Track_Event.element_name,
Counted_Events.counter,
Failure.fail_count, Failure.failure_date, Failure.descrip
FROM ORS.Track_Event
JOIN ORS.Switch_Operations
ON Switch_Operations.sequence_id = Track_Event.sequence_id
LEFT JOIN (SELECT element_name, COUNT(*) AS counter
FROM ORS.Track_Event
WHERE element_type = 'SWITCH'
AND event_type = 'I'
AND element_state IN ('NORMAL', 'REVERSE')
GROUP BY element_name) Counted_Events
ON Counted_Events.element_name = Switch_Operations.swicth_name
LEFT JOIN (SELECT switch_name,
COUNT(CASE WHEN no_correspondence = 1 THEN '1' END) AS fail_count,
MAX(CASE WHEN no_correspondence = 1 THEN command_time END) AS failure_date,
LISTAGG(description, ';' || CHAR(10)) WITHIN GROUP (ORDER BY command_time) AS descrip
FROM ORS.Switch_Operations
GROUP BY switch_name) Failure
ON Failure.switch_name = Track_Event.element_name
This query was written to (attempt to) preserve the semantics of your original query. I'm not completely sure that's what you actually need but without sample starting data and desired results, I have no way to tell how else to improve this. For instance, I'm a little suspicious of the need of Switch_Operations in the outer query, and the fact that LISTAGG(...) is run over row where no_correspondence <> 1. I did change the ordering of LISTAGG(...), because the original column would not have done anything (because the order way the same as the grouping), so would not have been a stable sort.
Single-row subquery returns more than one row.
This error message is self descriptive.
Returned field can't have multiple values and your subquery returns more than one row.
In your complete query you specify fields to be returned. The last field expects single value from the subquery but gets multiple rows instead.
I have no clue about the data you're working with but either you have to ensure that subquery returns only one row or you have to redesign the wrapping query (possibly using joins when appropriate).

SQL - updating Oracle 10g database from a complex query

trying to update a single column based on criteria. The rows that need to be updated are returned by the query
SELECT
it.objectid,
it.versionnumber,
it.itemnumber "Item Number",
it.itemtype,
itcovprem.basisofsettlement,
itcovprem.coverage "Coverage"
FROM
itemcoveragesandpremiums itcovprem,
items it,
policies pl
WHERE
pl.objectid = it.parentobjectid AND
pl.policytype in ('H','F') AND
it.objectid = itcovprem.itemobjectid AND
it.itemtype in ('SHOA','SHOB','SHOC','SHOD','SHOK','SHOL') and
it.versionnumber = itcovprem.itemversionnumber AND
((itcovprem.coverage like ('A - Dwg Bldg%')) or
(itcovprem.coverage like ('#42 - Repl Cost Plus%')) or
(itcovprem.coverage like ('#42 - Limited GRC%'))) and
it.effectivedate >= TO_DATE('01-JAN-2006', 'DD-MON-YYYY') and
exists (select * from itemcoveragesandpremiums icp where icp.itemobjectid = it.objectid and icp.itemversionnumber = it.versionnumber and icp.coverage like ('#42%')) and
itcovprem.basisofsettlement not in ('LGRC')
I've tried a few options to convert this to an update query, but no joy.
I get Error - line 3 - SQL command not properly ended when using
update itemcoveragesandpremiums
set basisofsettlement = 'LGRC'
from itemcoveragesandpremiums as itcovprem
inner join items as it
on it.objectid = itcovprem.itemobjectid and it.versionnumber = itcovprem.itemversionnumber
inner join policies as pl
on pl.objectid = it.parentobjectid
where [cut, rest of query was below]
I get Error - line 6 - missing right parenthesis when trying use an inline query
update
(
SELECT
itcovprem.basisofsettlement as OLD
FROM
itemcoveragesandpremiums as itcovprem inner join items as it on it.objectid = itcovprem.itemobjectid and it.versionnumber = itcovprem.itemversionnumber inner join policies AS pl on pl.objectid = it.parentobjectid
WHERE [query snipped]
) t
set t.old = 'LGRC'
Seems that SQL*Plus just wants to stop looking at the update before it gets to the meat of my select query. I'm not sure if I'm formatting it incorrectly or going at it from the wrong direction. Any advice?
In your first attempt, the error at line 3 is because update doesn't support a from or join clause. In your second attempt the immediate error at line 6 is because you're trying to alias a table with as itcovprem; but you can only use as for column aliases, not for table aliases. (The first attempt is trying to do that too, but it isn't getting as far as encountering that problem). But you can't generally update an inline-view with joins anyway, so it would still error with that - something like an ORA-01779.
You would need to do something like:
update itemcoveragesandpremiums
set basisofsettlement = 'LGRC'
where (itemobjectid, itemversionnumber, basisofsettlement, coverage) in (
select it.objectid,
it.versionnumber,
itcovprem.basisofsettlement,
itcovprem.coverage
from ...
)
Assuming that itemobjectid, itemversionnumber, basisofsettlement, coverage identifies a row sufficiently such that you don't risk updating anything you shouldn't. It might be safer to add a rowid to the select and use that for the update instead to avoid ambiguity:
update itemcoveragesandpremiums
set basisofsettlement = 'LGRC'
where rowid in (
select itcovprem.rowid as target_rowid
from ...
)