带有子查询的SQL Server VS mySQL更新

时间:2016-02-03 19:02:20

标签: mysql sql-server

一个简单的问题:

下面的更新查询在SQL Server中完美运行但在MySQL中失败。

MySQL err.msg = "Error Code: 1093. You can't specify target table 'Pos' for update in FROM clause".

我可以找到几种解决方法,但寻找最佳实践。

update Pos set Printed = 1 
where InvoiceNo = 3005 
and Status = 'N' 
and Pos.ItemNo IN 
(select Pos.ItemNo from Pos,ItemMaster 
where invoiceno = 3005 
and status = 'N' 
and printed = 0 
and catType in ('B','L') 
and Pos.itemno = ItemMaster.itemno)

1 个答案:

答案 0 :(得分:0)

这是"解决方法"我想出来了。由于我是从.NET应用程序调用的,因此我创建了一个执行JOB的存储过程。

DELIMITER //
CREATE PROCEDURE UpdatePrinted (IN varInvoiceNo VARCHAR(15))
 BEGIN

    DROP TEMPORARY TABLE IF EXISTS tmpParts;

    CREATE TEMPORARY TABLE tmpParts (tmpItemNo VARCHAR(20) NOT NULL);

    Insert Into tmpParts
    select Pos.ItemNo from Pos,ItemMaster 
    where invoiceno = varInvoiceNo 
    and status = 'N' 
    and printed = 0 
    and catType in ('B','L') 
    and Pos.itemno = ItemMaster.itemno;

    update Pos set Printed = 1 where InvoiceNo = varInvoiceNo and Status = 'N' and Pos.ItemNo IN (Select * from tmpParts);


 END //
DELIMITER ;