SQL SERVER:在一个update语句中有两个where条件

时间:2012-03-24 00:08:01

标签: sql sql-server

所以,我想用一个更新语句更新一个表。但是我有两个条件。意思是说有问题的表(tableA)有5列,其中3列用tableB更新,其余2用tableC更新。 例如:

update A
Set col1 = B.colx,
    col2 = B.coly,
    col3 = B.colz
From TableA A
  INNER JOIN TableB B
  ON A.col = B.colr
 Where B.colw = 'xx' AND B.colu = 'yy'


Update A
SET col4 = C.Cola
    col5 = C.Colb
FROM tableA A
 Inner join tableC C
 ON A.col= C.cols
WHERE C.colk= 'ddd' and C.colj = 'lll'

请帮忙!谢谢!

-------建议代码-----

我可以使用吗?

update A
    Set col1 = B.colx,
        col2 = B.coly,
        col3 = B.colz,
        col4 = C.Cola,
        col5 = C.Colb
    From TableA A
      INNER JOIN TableB B
      ON A.col = B.colr
          INNER JOIN TableC C
          ON A.col=C.cols
     Where (B.colw = 'xx' AND B.colu = 'yy') OR (C.colk= 'ddd' and C.colj = 'lll')

3 个答案:

答案 0 :(得分:0)

 update tableA
 set columnA = (select columnD from tableB
 where tableA.ID = tableB.ID),
 set columnB = (select columnD from tableC
 where tableA.ID = tableC.ID)
 where exists ... etc 

我同意这种方法没有太大的附加价值,而不是分成单独的DML语句。

答案 1 :(得分:0)

你可能正在寻找这样的事情:

update A 
left join B on( A.col = B.colr AND  B.colw = 'xx' AND B.colu = 'yy')
left join C on( A.col= C.cols AND C.colk= 'ddd' and C.colj = 'lll')
Set A.col1 = B.colx,
    A.col2 = B.coly,
    A.col3 = B.colz,
    A.col4 = C.Cola,
    A.col5 = C.Colb ;

答案 2 :(得分:-1)

可能是您无法从表中进行选择并同时更新它。

在数据库用语中选择意味着读取就像更新意味着写一样。

通过在“on”子句中指定:“A”,您正在读“A”

编辑:

 update A
Set col1 = B.colx,
    col2 = B.coly,
    col3 = B.colz,
    col4 = C.Cola,
    col5 = C.Colb
From (SELECT * FROM TableA) D, TableB B, TableC C
  WHERE D.col = B.colr
      AND D.col=C.cols
      AND ((B.colw = 'xx' AND B.colu = 'yy') OR (C.colk= 'ddd' and C.colj = 'lll'))