T-SQL查询以检查相关col是否为true并更新另一个表col

时间:2013-12-30 05:36:01

标签: sql sql-server

我有2个供应商订单和供应商订单详细信息,由SupplierOrder PK链接。现在我在SupplierOrder表中有一个名为isComplete的col,我希望在SupplierORderDetails表的isComplete中的所有值对于该supplierOrder ID都为true时更新为true。请参阅表格的附件。我已经尝试过这个查询,但我认为这可能是更好的方式或更有效率。

SELECT 1 
    FROM supplierOrder so
    inner JOIN supplierOrderdetails sod 
      ON so.id = sod.supplierOrderID
   WHERE so.id = 1
     AND sod.isComplete= 1 

enter image description here

2 个答案:

答案 0 :(得分:1)

这应该可行,我可能没有正确的表名,但是如果你改了它就应该有效

UPDATE suplierorder 
SET    iscomplete = 'true' 
WHERE  id IN (SELECT suplierorderid 
              FROM   (SELECT suplierorderid, 
--case statement to set to 0 if complete and 1 if not complete (i.e any other value null or false)
                             Sum(CASE 
                                   WHEN iscomplete = 'true' THEN 0 
                                   ELSE 1 
                                 END) AS complete 
                      FROM   suplierorderdetails 
                      --make sure we only update the new ones and makes sure that your select records are limited to Just not complete records, so if your tables grow this will make your update statement doesn't take a lot of time
                      WHERE  suplierorderid IN (SELECT id 
                                                FROM   suplierorder 
                                                WHERE  iscomplete IS NULL) 
--I am grouping on suplierorderid so that we can add all the iscomplete status of each  suplierorderid column
                      GROUP  BY suplierorderid) A 
--now that the inner query outputs suplierorderid and complete status which will be 0 if everything is complete we are writing below condition
              WHERE  complete = 0) 

答案 1 :(得分:1)

我们只需找到supplierOrderID MIN(isComplete)=1。所以这意味着所有isComplete=TRUE

UPDATE supplierOrder SET isComplete=1
WHERE id in
(
  SELECT supplierOrderID
  FROM supplierOrderdetails 
  GROUP BY supplierOrderID
  HAVING MIN(CAST(isComplete as Int))=1
)
AND 
(
 (isComplete is NULL ) OR (isComplete = 0) 
) 

SQLFiddle demo

PS:由于isCompleteBIT类型字段,因此您无法使用MIN(isComplete),但可以使用MIN(CAST(isComplete as Int))