更新联接

时间:2018-01-08 17:40:26

标签: sql sql-update

我可以简单地在联接中使用选择陈述来提取结果我喜欢使用:

Select * from RESULTS (NOLOCK) left join orders on Results.ordno = orders.ordno 
left join folders on folders.folderno = orders.folderno 
left join pranaparms on folders.prodcode = pranaparms.prodcode and results.analyte = pranaparms.analyte  
WHERE Results.s <> 'OOS-A' and Results.Final Between pranaparms.LOWERQCLIMIT  and pranaparms.UPPERQCLIMIT and (pranaparms.LOWERQCLIMIT IS NOT NULL and pranaparms.UPPERQCLIMIT IS NOT NULL) 
and results.ordno in (1277494) 

但是,有没有一种方便的方法可以对所选字段进行更新?

到目前为止我已尝试过这个:

Update RESULTS (NOLOCK) left join orders on Results.ordno = orders.ordno 
left join folders on folders.folderno = orders.folderno 
left join pranaparms on folders.prodcode = pranaparms.prodcode and results.analyte = pranaparms.analyte  
set Results.S = 'OOS-B'  
WHERE Results.s <> 'OOS-A' and Results.Final Between pranaparms.LOWERQCLIMIT  and pranaparms.UPPERQCLIMIT and (pranaparms.LOWERQCLIMIT IS NOT NULL and pranaparms.UPPERQCLIMIT IS NOT NULL) 
and results.ordno in (1277494)

但是,它传递的错误表明"Incorrect syntax near '('" 有没有办法让我更新这个连接,还是我需要单独做表?

1 个答案:

答案 0 :(得分:2)

您的select语法建议使用SQL Server。 SQL Server中的正确update语法是:

update r 
    set S = 'OOS-B'  
    from results r left join
         orders o
         on r.ordno = o.ordno left join
         folders f
         on f.folderno = o.folderno left join
         pranaparms p
         on f.prodcode = p.prodcode and r.analyte = p.analyte  
    where r.s <> 'OOS-A' and
          r.Final Between p.LOWERQCLIMIT and p.UPPERQCLIMIT and
          (p.LOWERQCLIMIT IS NOT NULL and p.UPPERQCLIMIT IS NOT NULL) and
          r.ordno in (1277494);

注意:

  • 表别名使查询更容易编写和阅读。
  • 除非您知道自己在做什么,否则请勿使用NOLOCK。鉴于您不知道正在使用的数据库update的语法规则,我猜您也不了解锁。
  • 您的WHERE条件正在将外连接转换为内连接。您应该只指定正确的join类型 - 并可能将条件移至on子句。我写完之时就已经离开了逻辑。