I am trying to update table A with data from table B. I thought I can do something like this
update A
set A.DISCOUNT = 3
from INVOICE_ITEMS A
join ITEM_PRICE_QUNTITY B on A.ITEM_PRICE_NO = B.ID
where A.INVOICE_ID = 33
but getting error SQL Message : -104 Invalid token
can anyone help me?
To UPDATE a table by joining multiple tables in SQL, let's create the two tables 'order' and 'order_detail. ' We can update the data of a table using conditions of other joined tables. It is possible to join two or more tables in an UPDATE query.
An UPDATE statement can include JOIN operations.
SQL Join generates a new (temporary or permanent) table from one or more tables by combining columns based on the way the Join is invoked. There's also a “self-join” variant to groom an unruly table into something more manageable.
Multiple-table UPDATE statements can use any type of join allowed in SELECT statements, such as LEFT JOIN.
It is not possible to do this with a JOIN
. The Firebird UPDATE
statement has no FROM
clause. The syntax is:
UPDATE {tablename | viewname} [[AS] alias]
SET col = newval [, col = newval ...]
[WHERE {search-conditions | CURRENT OF cursorname}]
[PLAN plan_items]
[ORDER BY sort_items]
[ROWS <m> [TO <n>]]
[RETURNING <values>]
<m>, <n> ::= Any expression evaluating to an integer.
<values> ::= value_expression [, value_expression ...]
<variables> ::= :varname [, :varname ...]
However the equivalent of your example query is:
update INVOICE_ITEMS
set DISCOUNT = 3
WHERE EXISTS (SELECT 1 FROM ITEM_PRICE_QUNTITY B WHERE B.ID = ITEM_PRICE_NO)
AND INVOICE_ID = 33
If you want to update using data from additional tables, you might want to consider using MERGE
. In your comment you ask for the equivalent query to do the following with Firebird:
UPDATE B
SET B.QUANTIY = b.QUANTIY + a.QUANTITY
FROM ITEM_PRICE_QUNTITY B JOIN INVOICE_ITEMS A ON A.ITEM_PRICE_NO = B.ID
WHERE A.INVOICE_ID = 33
The equivalent MERGE
statement would be:
MERGE INTO ITEM_PRICE_QUNTITY AS B
USING INVOICE_ITEMS AS A
ON A.ITEM_PRICE_NO = B.ID AND A.INVOICE_ID = 33
WHEN MATCHED THEN
UPDATE SET B.QUANTIY = B.QUANTIY + A.QUANTITY
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With