在SQL中同时更新多个表

时间:2016-06-21 23:09:47

标签: sql sql-server sql-server-2008

我有像

这样的表格查询
renderRow(session: Session, day: number)

此处UPDATE D SET D.VALUE = B.VALUE FROM DOM D INNER JOIN COM C ON C.ID = D.ID INNER JOIN TOM T ON T.ID = D. ID WHERE D.VALUE <> B.VALUE UPDATE D SET C.VALUE = B.VALUE FROM DOM D INNER JOIN COM C ON C.ID = D.ID INNER JOIN TOM T ON T.ID = D. ID WHERE D.VALUE <> B.VALUE 条件对于两个查询都是相同的,并且连接也是相同的。那么我可以使用一个where语句更新这两个表吗?

2 个答案:

答案 0 :(得分:3)

您无法使用一个Update语句更新TWO表。但是您可以通过将两个单独的更新包装到一个事务中来更新一个事务中的两个表。它实现了相同的目标,但方式略有不同。

BEGIN TRANSACTION 

    UPDATE D 
     SET D.VALUE = B.VALUE
    FROM 
    DOM D 
    INNER JOIN COM C ON C.ID = D.ID
    INNER JOIN TOM T ON T.ID = D. ID
    WHERE D.VALUE <> B.VALUE

    UPDATE D 
       SET C.VALUE = B.VALUE
    FROM 
    DOM D 
    INNER JOIN COM C ON C.ID = D.ID
    INNER JOIN TOM T ON T.ID = D. ID
    WHERE D.VALUE <> B.VALUE

COMMIT TRANSACTION 

答案 1 :(得分:0)

最明显的解决方案是在DOM表上编写Update触发器。此触发器将处理TOM和COM表。

Select 1 ID, 10 Value
into DOM
union all
Select 2, 20
union all
Select 3, 30


Select 1 ID, 10 Value
into TOM
union all
Select 2, 20
union all
Select 3, 30


Select 1 ID, 10 Value
into COM
union all
Select 2, 20
union all
Select 3, 30


drop trigger DomUpdate 
create trigger DomUpdate on DOM 
after Update
as 
begin
Update TOM 
set value = i.value 
from TOM t
INNER JOIN 
    inserted I ON I.ID = T. ID

Update COM 
set value = i.value 
from TOM t
INNER JOIN 
    inserted I ON I.ID = T. ID
end
GO

Select D.value 
FROM 
    DOM D 
INNER JOIN 
    COM C ON C.ID = D.ID
INNER JOIN 
    TOM T ON T.ID = D. ID
WHERE
    D.VALUE <> 50

begin tran t1
Update D
set D.value = 50
FROM 
    DOM D 
INNER JOIN 
    COM C ON C.ID = D.ID
INNER JOIN 
    TOM T ON T.ID = D. ID
WHERE
    D.VALUE <> 50
--rollback tran t1
commit tran t1

Select * from DOM
Select * from COM
Select * from TOM