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

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

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;

Combine update statement and select statement

I'm using Oracle SQL Developer and I'm trying combine an update and a select statment into one. I know that Oracle dosen't support FROM or JOINS directly in the update statement and I therefor put the select in a subquery but it still don't work.
I have got two tables; MASTERTABLE and TESTTABLE.
MASTERTABLE contain an ID_NUMBER column and a TESTTABLE_ID column.
TESTTABLE contains a TESTTABLE_ID column and a TEST_COLUMN column.
What I want to do is to update the TEST_COLUMN value while only knowing the ID_NUMBER.
What my statement looks like:
UPDATE TESTTABLE
SET TEST_COLUMN= 'Testvalue'
WHERE TESTTABLE.TESTTABLE_ID IN (SELECT MASTERTABLE.TESTTABLE_ID
FROM MASTERTABLE
WHERE ID_NUMBER=11);
But I get stuck in some kind of loop. Where did I go wrong?
I have faced the same problem. The solution is usage of MERGE operation instead of UPDATE.
MERGE INTO TESTTABLE t
USING
(
SELECT m.ID_NUMBER num,
m.TESTTABLE_ID id
FROM MASTERTABLE m
) newnum ON (t.TESTTABLE_ID = newnum.id)
WHEN MATCHED THEN UPDATE
SET t.TEST_COLUMN = newnum.num;
You can try any one of this in Oracle
Normal Update
UPDATE
TESTTABLE
SET
TEST_COLUMN= 'Testvalue'
WHERE
EXISTS
(SELECT MASTERTABLE.TESTTABLE_ID
FROM MASTERTABLE
WHERE ID_NUMBER=11);
Using Inline View (If it is considered updateable by Oracle)
Note: If you face a non key preserved row error add an index to resolve the same to make it update-able
UPDATE
(SELECT
TESTTABLE.TEST_COLUMN AS OLD,
'Testvalue' AS NEW
FROM
TESTTABLE
INNER JOIN
MASTERTABLE
ON TESTTABLE.TESTTABLE_ID = MASTERTABLE.TESTTABLE_ID
WHERE ID_NUMBER=11) T
SET
T.OLD = T.NEW;
Using Merge
MERGE INTO
TESTTABLE
USING
(SELECT
T1.ROWID AS RID,
T2.TESTTABLE_ID
FROM
TESTTABLE T1
INNER JOIN
MASTERTABLE T2
ON TESTTABLE.TESTTABLE_ID = MASTERTABLE.TESTTABLE_ID
WHERE ID_NUMBER=11)
ON
( ROWID = RID )
WHEN MATCHED
THEN
UPDATE SET TEST_COLUMN= 'Testvalue';
The problem was as Tom H wrote a blocking problem. When I started working on the project today all of the solutions worked.

Oracle SQL, trying to get one value from a select/join to use to update one column in one table?

I have one table with the following columns:
T_RESOLVED_DATE
I_HOUSEHOLD_NUMBER
I_RESOLVED_SET_NUMBER
I_STATION_CODE
I_RESOLVED_START_MIN
I_DURATION
I_PERSON_NUMBER
I_COVIEW_DEMO_ID
Initially, I_COVIEW_DEMO_ID is set to null.
Then I have another table with the following columns:
T_RESOLVED_DATE
I_HOUSEHOLD_NUMBER
I_PERSON_NUMBER
I_AGE
T_GENDER
I_COVIEW_DEMO_ID
I am trying to update I_COVIEW_DEMO_ID in the first table by using the value of I_COVIEW_DEMO_ID in the second table where the T_RESOLVED_DATE, I_HOUSEHOLD_NUMBER, and I_PERSON_NUMBER are equal in both tables. The first table may contain multiple rows with the same DATE, HOUSEHOLD_NUMBER, and PERSON_NUMBER, because the rows can vary by the rest of the columns.
I have tried to do a select and a group by which seems to get me part way there, but I am getting a "single-row subquery returns more than one row" error when I try to update the columns in the first table. This is what I've tried, along with variations of it:
UPDATE
Table1
SET
I_COVIEW_DEMO_ID =
(SELECT
b.I_COVIEW_DEMO_ID
FROM Table1 a,
Table2 b
WHERE a.I_HOUSEHOLD_NUMBER = b.I_HOUSEHOLD_NUMBER AND
a.I_PERSON_NUMBER = b.I_PERSON_NUMBER AND
a.T_RESOLVED_DATE = b.T_RESOLVED_DATE
GROUP BY b.I_COVIEW_DEMO_ID);
Any suggestions?
I was able to get it to work using this statement:
MERGE INTO table1 a
USING
(
SELECT DISTINCT
T_RESOLVED_DATE,
I_HOUSEHOLD_NUMBER,
I_PERSON_NUMBER,
I_COVIEW_DEMO_ID
FROM
table2
) b
ON
(
a.T_RESOLVED_DATE = b.T_RESOLVED_DATE
AND a.I_HOUSEHOLD_NUMBER = b.I_HOUSEHOLD_NUMBER
AND a.I_PERSON_NUMBER = b.I_PERSON_NUMBER
) WHEN MATCHED THEN
UPDATE SET
a.I_COVIEW_DEMO_ID = b.I_COVIEW_DEMO_ID;
As per our discussion on the comments this would be a simple PLSQL block to do what you need. I'm doing direct from my head without test, so you may need to fix some sintaxe mistake.
BEGIN
FOR rs IN ( SELECT I_HOUSEHOLD_NUMBER,
I_PERSON_NUMBER,
I_COVIEW_DEMO_ID,
T_RESOLVED_DATE
FROM Table2 ) LOOP
UPDATE Table1
SET I_COVIEW_DEMO_ID = rs.I_COVIEW_DEMO_ID
WHERE I_PERSON_NUMBER = rs.I_PERSON_NUMBER
AND I_HOUSEHOLD_NUMBER = rs.I_HOUSEHOLD_NUMBER
AND T_RESOLVED_DATE = rs.T_RESOLVED_DATE;
END LOOP;
--commit after all updates, if there is many rows you should consider in
--making commits by blocks. Define a count and increment it whithin the for
--after some number of updates you commit and restart the counter
COMMIT;
END;

Update Table from a subquery

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'

T-SQL cursor and update

I use a cursor to iterate through quite a big table. For each row I check if value from one column exists in other.
If the value exists, I would like to increase value column in that other table.
If not, I would like to insert there new row with value set to 1.
I check "if exists" by:
IF (SELECT COUNT(*) FROM otherTabe WHERE... > 1)
BEGIN
...
END
ELSE
BEGIN
...
END
I don't know how to get that row which was found and update value. I don't want to make another select.
How can I do this efficiently?
I assume that the method of checking described above isn't good for this case.
Depending on the size of your data and the actual condition, you have two basic approaches:
1) use MERGE
MERGE TOP (...) INTO table1
USING table2 ON table1.column = table2.column
WHEN MATCHED
THEN UPDATE SET table1.counter += 1
WHEN NOT MATCHED SOURCE
THEN INSERT (...) VALUES (...);
the TOP is needed because when you're doing a huge update like this (you mention the table is 'big', big is relative, but lets assume truly big, +100MM rows) you have to batch the updates, otherwise you'll overwhelm the transaction log with one single gigantic transaction.
2) use a cursor, as you are trying. Your original question can be easily solved, simply always update and then check the count of rows updated:
UPDATE table
SET column += 1
WHERE ...;
IF ##ROW_COUNT = 0
BEGIN
-- no match, insert new value
INSERT INTO (...) VALUES (...);
END
Note that this approach is dangerous though because of race conditions: there is nothing to prevent another thread from inserting the value concurrently, so you may end up with either duplicates or a constraint violation error (preferably the latter...).
This is just psuedo code because I have no idea of your table structure but I think you will understand... basically Update the columns you want then Insert the columns you need. A Cursor operation sounds unnecessary.
Update OtherTable
Set ColumnToIncrease = ColumnToIncrease + 1
FROM CurrentTable Where ColumnToCheckValue is not null
Insert Into OtherTable (ColumnToIncrease, Field1, Field2,...)
SELECT
1,
?
?
FROM CurrentTable Where ColumnToCheckValue is not null
Without a sample, I think this is the best I can do. Bottom line: you don't need a cursor. UPDATE where a match exists (INNER JOIN) and INSERT where one does not.
UPDATE otherTable
SET IncrementingColumn = IncrementingColumn + 1
FROM thisTable INNER JOIN otherTable ON thisTable.ID = otherTable.ID
INSERT INTO otherTable
(
ID
, IncrementingColumn
)
SELECT ID, 1
FROM thisTable
WHERE NOT EXISTS (SELECT *
FROM otherTable
WHERE thisTable.ID = otherTable.ID)
I think you'd be better off using a view for this -- then it's always up to date, no risk of mistakenly double/triple/etc counting:
CREATE VIEW vw_value_count AS
SELECT st.value,
COUNT(*) AS numValue
FROM SOME_TABLE st
GROUP BY st.value
But if you still want to use the INSERT/UPDATE approach:
IF EXISTS(SELECT NULL
FROM SOMETABLE WHERE ... > 1)
BEGIN
UPDATE TABLE
SET count = count + 1
WHERE value = #value
END
ELSE
BEGIN
INSERT INTO TABLE
(value, count)
VALUES
(#value, 1)
END
What about Update statement with inner join to perform +1, and Insert selected rows that do not exist in the first table.
Provide the tables schema and the columns you want to check and update so I can help.
Regards.