Update Table from a subquery - sql

In the statement below, I'm trying to normalize LocationIDs in the table 'Replies' based off the data I retrieve from the subquery SELECT statement. Basically, there are LocationIDs in the Replies table that are not in the MasterList, I would like to replace those occurances with the location of '1234'. I figured the statement below would work, but it doesn't. When I attempt to run it, it updates all the LocationID's in the Replies tables after May 5th, 2010.
UPDATE Replies
SET Replies.LocationID = '1234'
FROM (SELECT lml.LocationID FROM Replies sfs LEFT JOIN MasterList lml ON lml.LocationID=sfs.LocationID WHERE sfs.CreateDate >= '5/5/2010') AS rs
WHERE rs.LocationID is null

You can use the not exists clause to find locations that do not exists on masterList as
update replies
set locationid='1234'
where not exists (
select 1 from masterlist as ml
where
ml.locationid=replies.locationid
)
and CreateDate >= '5/5/2010'

Related

Updating all the record for a column in a table with value from another table

Hi I want to update all the values of RequestId column of IIL_CHANGE_REQUEST Table with the RequestId of TABLE_NAME_4MINS Table where REQUESTBY column in both tables are same. I am trying to do this in oracle daatabalse(sql developer)
My query:
Update IIL_CHANGE_REQUEST
set REQUESTID=(SELECT TABLE_NAME_4MINS.REQUESTID
FROM TABLE_NAME_4MINS
WHERE IIL_CHANGE_REQUEST.REQUESTBY = TABLE_NAME_4MINS.REQUESTBY)
WHERE EXISTS (SELECT TABLE_NAME_4MINS.REQUESTID
FROM TABLE_NAME_4MINS
WHERE IIL_CHANGE_REQUEST.REQUESTBY = TABLE_NAME_4MINS.REQUESTBY)
But every time I do this I get an error saying:
Error starting at line : 1 in command -
Update IIL_CHANGE_REQUEST
set REQUESTID=(SELECT TABLE_NAME_4MINS.REQUESTID
FROM TABLE_NAME_4MINS
WHERE IIL_CHANGE_REQUEST.REQUESTBY = TABLE_NAME_4MINS.REQUESTBY)
WHERE EXISTS (SELECT TABLE_NAME_4MINS.REQUESTID
FROM TABLE_NAME_4MINS
WHERE IIL_CHANGE_REQUEST.REQUESTBY = TABLE_NAME_4MINS.REQUESTBY)
Error report -
ORA-01427: single-row subquery returns more than one row
Please anyone help how can I do it.
It depends on what you want to do in such cases. If you don't really care, take any value, for example minimum:
update iil_change_request a
set a.requestid = (select min(b.requestid) --> here
from table_name_4mins b
where a.requestby = b.requestby)
where exists (select c.requestid
from table_name_4mins c
where a.requestby = c.requestby);
If that's not what you want, then you'll have to figure out what to do with those "duplicates". Perhaps you'll have to include yet another WHERE condition, or fix data, or ... who knows? I don't, while you should.
You need to find a condition to narrow down returned rows to the only per REQESTSTBY, for example you can replace ... with a column name in the query below to return just first row as per order-by:
MERGE INTO IIL_CHANGE_REQUEST r
USING (
SELECT *
FROM (
SELECT REQUESTBY, REQUESTID
,row_number()over(partition by REQUESTBY order by ...) rn
FROM TABLE_NAME_4MINS
)
where rn=1
) t
ON (r.REQUESTBY = t.REQUESTBY)
WHEN MATCHED THEN UPDATE
set REQUESTID=t.REQUESTID;

update tbl_1 set tbl_1.valueA = tbl2.valueB when tbl_2.valueC is equal to tbl_1valueD

As the title indicates - I'm trying to update a table.value with another table.value based on a common value in the 2 tables (but not same column names)
First I delete any duplicate records in the source table.
And count the remaining rows - that total is 93.
Select rowid, xfmid_value from w_valve_reftest;
Delete from w_valve_reftest a
where rowid> (select min(rowid)
from w_valve_reftest b where b.xfmid_value=a.XFMID_VALUE);
Select count(*) from w_valve_reftest;
Next I want to update the target.reference_1 with the value from source.ref1_value and target.reference_2 with source.ref2_value where source.xfmid_value=target.xfm_id
Here is what I have, but for some reason it is updating 17,000+ records. Rather than the 93 I expect.
update w_isolationvalve
set w_isolationvalve.reference_1=(select ref1_value from w_valve_reftest where w_isolationvalve.xfm_id=w_valve_reftest.xfmid_value);
update W_isolationvalve
set w_isolationvalve.reference_2=(select ref2_value from w_valve_reftest where w_isolationvalve.xfm_id=w_valve_reftest.xfmid_value);
I'm no expert, but not a rookie any longer. I've hacked it this far using google. Thanks for any assist.
Your second query should be:
update a
set reference_1=b.ref1_value,
refrence_2=b.ref2_value
FROM w_isolationvalve a
JOIN w_valve_reftest b ON a.xfm_id=b.xfmid_value
As for the update counts, it will only be 93 only if xfm_id and xfmid_value are unique.
Also be careful of non-deterministic updates.
If your select will have multiple results for your join condition, the update will be executed once for each of the multiple results and you will not know what you end up with.
This should work in Oracle:
MERGE INTO w_isolationvalve a
USING
(
SELECT * FROM w_valve_reftest
)b
ON(a.xfm_id = b.xfmid_value)
WHEN MATCHED THEN UPDATE SET
a.reference_1 = b.ref1_value,
a.refrence_2 = b.ref2_value ;
Since you do not like merge. I think this should also work in Oracle:
UPDATE
(SELECT a.reference_1, a.refrence_2, b.ref1_value , b.ref2_value
FROM w_isolationvalve a
INNER JOIN w_valve_reftest b
ON a.xfm_id = b.xfmid_value
) t
SET t.reference_1 = t.ref1_value ,
t.refrence_2 =t.ref2_value

SQL Update only updates one row

This code is only updating one row, why? It has to do with one of the sub-queries but I am not sure. I'm thinking the WHERE..IN in the UPDATE statement but I am not sure.
UPDATE [sde].[sy1].[Valve_evw]
SET [sde].[sy1].[Valve_evw].[MA]
= (SELECT [sde].[sy1].[Valve_Join_evw].[MC]
FROM [sde].[sy1].[Valve_Join_evw])
WHERE [sde].[sy1].[Valve_evw].[PrimaryKey]
IN (SELECT [sde].[sy1].[Valve_Join_evw].[PrimaryKey]
FROM [sde].[sy1].[Valve_Join_evw]
WHERE [sde].[sy1].[Valve_Join_evw].[MA]
!= [sde].[sy1].[Valve_Join_evw].[MC])
Context:
What I am trying to do is update the MA column in Valve_evw using the MC column in Valve_Join_evw. The PrimaryKey in Valve_evw references equivalent rows as the PrimaryKey in Valve_Join_evw. As in, a single row in Valve_Join_evw will have the same PrimaryKey as a single row in Valve_evw, thus that equivalency can be used to update the records in Valve_evw. Also the MA column is equivalent in both tables. [Note: The Valve_Join_evw table is created with ESRI mapping software using the spatial relationship between the Valve_evw and a separate table, this is how the duplicate rows exist]
I am using database views (hence the '_evw') in SQL Server with a default INSTEAD OF UPDATE trigger. This combination, views and trigger, prevents the use of table joins to do this update. I have also tried MERGE but that will not work either. Therefore I am stuck with the ANSI standard, hence the sub-queries. This script runs with no errors but it only updates a single row whereas there are about 9000 thousand rows in the tables.
The output message:
(1 row(s) affected)
(0 row(s) affected)
First of all let's reduce the eye hurting SQL to what it really is:
update sde.sy1.valve_evw
set ma = (select mc from sde.sy1.valve_join_evw)
where primarykey in (select primarykey from sde.sy1.valve_join_evw where ma <> mc)
WHERE clause
We look for all primarykey in valve_join_evw where a record's ma <> mc. We update all valve_evw records with such primarykey.
SET clause
For a record we want to update, we set ma to the value found with:
select mc from sde.sy1.valve_join_evw
But this query has no where clause, so what value does it select to fill the record's ma field? It selects all mc from valve_join_evw, so the DBMS probably picks one of these values arbitrarily. (It would be better, it raised an error.)
Conclusion
It is very easy to see which records the statement will update.
Which primarykey:
select primarykey from sde.sy1.valve_join_evw where ma <> mc
Which rows:
select *
from sde.sy1.valve_evw
where primarykey in (select primarykey from sde.sy1.valve_join_evw where ma <> mc)
As to the SET clause: Add a WHERE clause to your subquery that relates the record to select to the record to update (same ma? same primarykey?) E.g.:
set ma =
(
select mc
from sde.sy1.valve_join_evw vj
where vj.primarykey = valve_evw.primarykey
and vj.ma = valve_evw.ma
)
Hi there i recomend first to do the select statement and when you are ok with te records retrieved use the same where for the update statement
Here is what the final script looks like.
UPDATE [Valve_evw]
SET [Valve_evw].[MA] =
(
SELECT [Valve_Join_evw].[MC]
FROM [Valve_Join_evw]
WHERE[Valve_Join_evw].[PrimaryKey] = [Valve_evw].[PrimaryKey]
)
WHERE [Valve_evw].[PrimaryKey]
IN (
SELECT [Valve_Join_evw].[PrimaryKey]
FROM [Valve_Join_evw]
WHERE [Valve_Join_evw].[MA]
!= [Valve_Join_evw].[MC]
);

Update largest date, matching two fields

tables
Hi, I'm looking to update the last column in a blank table. Picture shows input and desired output. Trying to pick the largest date where workorder and state match.
I've tried a couple different codes:
UPDATE mytable
SET mytable.orderstartdate = MAX(table2.earliestdate)
FROM mytable as table2
WHERE (mytable.workorder = table2.workorder AND
mytable.state = table2.state)
;
"Syntax Error (missing operator) in query expression 'MAX(table2.earliestdate) FROM mytable as table2'."
UPDATE mytable
SET mytable.orderstartdate = (
SELECT max(earliestdate)
FROM mytable as table2
WHERE (mytable.workorder = table2.workorder AND
mytable.state = table2.state)
)
;
"Operation must use an updateable query"
Edit - click tables link for image.
Write PL/SQL Code.
First, select DISTINCT WorkOrder and State and capture in variables.
Now, Iterate the list and Write a query to get max date i.e. max(date) using work_order and State in where clause. Capture the
date.
Now, In the same loop write update query setting max(date) and workorder and State in where clause.
UPDATE table A
SET A.orderstartDate = (SELECT max(earliestdate)
FROM table B
WHERE A.WorkOrder = B.WorkOrder
GROUP BY WorkOrder)
not sure if access supports correlated subqueries but if it does...
and if not...
UPDATE table A
INNER JOIN (SELECT WorkOrder, max(OrderStartDate) MOSD
FROM Table B
GROUP BY WorkOrder) C
ON A.WorkOrder = C.workOrder
SET A.OrderStartDate = C.MOSD
Check database open mode, it may be locked for editing, or you may have no permission to to file.

Writing a single UPDATE statement that prevents duplicates

I've been trying for a few hours (probably more than I needed to) to figure out the best way to write an update sql query that will dissallow duplicates on the column I am updating.
Meaning, if TableA.ColA already has a name 'TEST1', then when I'm changing another record, then I simply can't pick a value for ColA to be 'TEST1'.
It's pretty easy to simply just separate the query into a select, and use a server layer code that would allow conditional logic:
SELECT ID, NAME FROM TABLEA WHERE NAME = 'TEST1'
IF TableA.recordcount > 0 then
UPDATE SET NAME = 'TEST1' WHERE ID = 1234
END IF
But I'm more interested to see if these two queries can be combined into a single query.
I am using Oracle to figure things out, but I'd love to see a SQL Server query as well. I figured a MERGE statement can work, but for obvious reasons you can't have the clause:
..etc.. WHEN NOT MATCHED UPDATE SET ..etc.. WHERE ID = 1234
AND you can't update a column if it's mentioned in the join (oracle limitation but not limited to SQL Server)
ALSO, I know you can put a constraint on a column that prevents duplicate values, but I'd be interested to see if there is such a query that can do this without using constraint.
Here is an example start-up attempt on my end just to see what I can come up with (explanations on it failed is not necessary):
ERROR: ORA-01732: data manipulation operation not legal on this view
UPDATE (
SELECT d.NAME, ch.NAME FROM (
SELECT 'test1' AS NAME, '2722' AS ID
FROM DUAL
) d
LEFT JOIN TABLEA a
ON UPPER(a.name) = UPPER(d.name)
)
SET a.name = 'test2'
WHERE a.name is null and a.id = d.id
I have tried merge, but just gave up thinking it's not possible. I've also considered not exists (but I'd have to be careful since I might accidentally update every other record that doesn't match a criteria)
It should be straightforward:
update personnel
set personnel_number = 'xyz'
where person_id = 1001
and not exists (select * from personnel where personnel_number = 'xyz');
If I understand correctly, you want to conditionally update a field, assuming the value is not found. The following query does this. It should work in both SQL Server and Oracle:
update table1
set name = 'Test1'
where (select count(*) from table1 where name = 'Test1') > 0 and
id = 1234