用连接更新表?

时间:2014-07-17 09:55:43

标签: sql firebird firebird2.5

我正在尝试使用表B中的数据更新表A. 我以为我可以做这样的事情

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

但是收到错误 SQL消息:-104 令牌无效

任何人都可以帮助我吗?

4 个答案:

答案 0 :(得分:9)

使用JOIN无法执行此操作。 Firebird UPDATE语句没有FROM子句。 syntax是:

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 ...]

但是,您的示例查询的等价物是:

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

如果要使用其他表中的数据进行更新,可能需要考虑使用MERGE。在您的评论中,您要求使用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

等效的MERGE语句为:

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 

答案 1 :(得分:1)

从FB手册开始,如果您使用的是Firebird 2.0或更高版本,则可以使用EXECUTE BLOCK编写更有效的语句:

EXECUTE BLOCK
AS
DECLARE VARIABLE field1 type;
DECLARE VARIABLE field2 type;
-- ...etc.
DECLARE VARIABLE pk type;
BEGIN
   for select pk, field1, field2, ... from src_table
   into :pk, :field1, :field2, ...
   do update dest_table set field1 = :field1, field2 = :field2, -- ...
   where pk = :pk;
END

答案 2 :(得分:0)

由于FROM子句,您可能会出错。您可以不用使用 FROM子句来做到这一点。这是一个示例:

    UPDATE customer_table c 

      JOIN  
          employee_table e
          ON c.city_id = e.city_id  
      JOIN 
          anyother_ table a
          ON a.someID = e.someID

    SET c.active = "Yes"

    WHERE c.city = "New york";

答案 3 :(得分:-1)

你可以像这样使用:

update INVOICE_ITEMS  
set DISCOUNT = 3 
from (select * from ITEM_PRICE_QUNTITY ) b
where INVOICE_ITEMS.ITEM_PRICE_NO = B.ID and 
INVOICE_ITEMS.INVOICE_ID = 33