如何更新2个表中的记录但是必须先满足条件?

时间:2014-03-25 22:12:49

标签: sql-server

我正在尝试更新表中的列以获取另外两个表中的记录,但它必须满足4个条件。

Table1:
    Caller_company |  client_id | risk_weight_factor | area_id
        Potter     |       3    |         5          |    1
        Potter     |       3    |         7          |    2

Table2:
    Locate_request_id | caller_company | area_id
         7755329      |   Potter       |    1
         7769761      |   Potter       |    3

Table3:
    Locate_request_id | client_id | risk_factor
         7755329      |    3      |      2
         7769761      |    3      |      4

条件:

  1. table1.locate_request_id = table3.locate_request_id
  2. table3.client_id = 3
  3. table2.area_id = 1
  4. table2.caller_company ='波特'
  5. 如果符合条件,那么它将从表1中提取risk_weight_factor值,然后通过将table1.risk_weight_factor与table3.risk_factor

    一起更新来更新table3.risk_factor列。
      

    table3.risk_factor = table3.risk_factor +   table1.risk_weight_factor

    UPDATE table3
    SET [risk_factor] = table3.risk_factor + table1.risk_weight_factor
    WHERE table2.locate_request_id = table3.locate_request_id
    and 
    table3.dpra_client_id = 3
    and
    table2.lac_area_id = 1
    (
    table1.caller_company LIKE 'potter' THEN table3.risk_factor+table1.risk_weight_factor);
    

    我是SQL新手,我知道我的陈述没有意义。如果有人可以帮忙解决这个问题,我将非常感激!

2 个答案:

答案 0 :(得分:1)

试试这个

Update T3
set T3.risk_factor=T3.risk_factor+T1.risk_weight_factor
from
table3 T3
inner join table2 T2 on T2.Locate_request_id=T3.Locate_request_id
inner join table1 T1 on T1.area_id=T2.area_id
where
T3.client_id = 3 and
T2.area_id = 1 and
T2.caller_company = 'potter'

连接将返回表中匹配的值,而where子句将取出奇数。

答案 1 :(得分:0)

第4个条件中的更新语句具有的内容超出了您指定的条件。如果您指定的条件为真,那么udpate语句将是这样的:

UPDATE table3
SET [risk_factor] = table3.risk_factor + table1.risk_weight_factor
WHERE table2.locate_request_id = table3.locate_request_id
and 
table3.dpra_client_id = 3
and
table2.lac_area_id = 1
and
table1.caller_company = 'potter'