尝试在SQL存储过程中将多个UPDATE语句合并为一个

时间:2013-12-28 01:14:37

标签: sql-server-2008 stored-procedures sql-update left-join

我在存储过程中有多个更新语句(如下所示)。

问题是我正在尝试将它们合并到一个UPDATE语句中,因为存在性能问题(执行存储过程需要更长时间)。我尝试将列(例如PONUMBER,VENDORID等)放在一个更新语句中,但它会抛出错误。

请建议。

     UPDATE rptMaster SET  PONUMBER = (select top 1 poMaster.PONUMBER from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and 
        poMaster.UnCommited > 0)

    UPDATE rptMaster SET  VENDORID = (select top 1 poMaster.VENDORID from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and 
    poMaster.UnCommited > 0)

    UPDATE rptMaster SET  DUEDATE = (select top 1 poMaster.REQDATE from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and 
    poMaster.UnCommited > 0)

    UPDATE rptMaster SET  POQTYORDER = (select top 1 (poMaster.QTYORDER / rptMaster.UOMQTY) from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and 
    poMaster.UnCommited > 0)

2 个答案:

答案 0 :(得分:1)

我和polkduran的相似:

 WITH PO AS (
     SELECT  PONUMBER
        ,    VENDORID
        ,    REQDATE
        ,    QTYORDER
        ,    ITEMNMBR
        ,    ROW_NUMBER() OVER (PARTITION BY ITEMNMBR ORDER BY ??) as RN
     FROM    poMaster
     WHERE   UnCommited > 0
    )
 UPDATE rptMaster 
 SET  PONUMBER = po.PONUMBER
 ,    VENDORID = po.VENDORID 
 ,    DUEDATE = po.REQDATE
 ,    POQTYORDER = po.QTYORDER / rptMaster.UOMQTY
 FROM rptMaster
     JOIN PO
          ON  PO.ITEMNMBR = rptMaster.ITEMNMBR 
          and PO.RN = 1

我正在使用公用表表达式(CTE)为每个poMaster记录分配行号,每个值ITEMNMBR的记录分别编号。这样我们就可以选择ITEMNBRJOIN的每个??的第一条记录,类似于您在子查询中使用Top 1的方式。

请注意,但是:因为您没有说明如何在查询中选择Top 1记录,所以我不得不在CTE中保留ORDER BY子句。 (我将??作为占位符。)您需要指定一个或多个排序字段来代替{{1}},以便它知道如何对记录进行排序和编号。

答案 1 :(得分:0)

您可以使用join子句进行更新:

update rpt
set
    PONUMBER = po.PONUMBER,
    VENDORID = po.VENDORID,
    DUEDATE = po.REQDATE,
    POQTYORDER = (po.QTYORDER / rpt.UOMQTY)
from rptMaster rpt
inner join poMaster po
    on po.ITEMNMBR = rpt.ITEMNMBR
where po.UnCommited > 0

我现在没有办法测试它,但这可能有用。