2016-11-14 68 views
0

我即三個表:mysql的觸發器不WAMP的服務器上的工作

  1. tab_m_blood
  2. tab_m_donar
  3. tab_t_bloodstock

「tab_m_blood」 條目下面:

bgId  | bGroup 
    -------------------- 
    1   | A+ 
    2   | A- 
    3   | B+ 
    4   | B- 
    5   | AB+ 
    6   | AB- 
    7   | O+ 
    8   | O- 

tab_m_donar條目低於:

dId | donarName | donarAddress | donarContact | donarDisease | bgId | bloodUnit 
--------------------------------------------------------------------------------- 
1 | a   | xy   | 111   | NA   | 2 | 20 
2 | b   | uv   | 222   | NA   | 2 | 30 

tab_t_bloodstock條目下面:

bgId | bUnit 
    ------------ 
    1 | 0 
    2 | 0 
    3 | 0 
    4 | 0 
    5 | 0 
    6 | 0 
    7 | 0 
    8 | 0 
  1. 我要的是,當一個Donar已捐出自己的血「tab_m_donar」,血液庫存相應的血型將更新「tab_t_bloodstock」
  2. 我想在「tab_m_donar」上寫一個觸發器,就像任何數據將插入「tab_m_donar」時那樣,數據將更新「tab_t_bloodstock」。
  3. 「tab_t_bloodstock」中的「bgId」是「tab_m_blood」中PK - >「bgId」的FK。

我已經寫了下面的扳機,但它不工作:

CREATE TRIGGER updatestock AFTER UPDATE ON tab_m_doner 
FOR EACH ROW 
begin 
if old.bgId is not null then 
update tab_t_bloodstock 
set bUnit=bUnit-old.bloodUnit 
where bgId=old.bgId; 
end if; 
if new.bgId is not null then 
update tab_t_bloodstock 
set bUnit=bUnit+new.bloodUnit 
where bgId=new.bgId; 
end if; 
end 

請幫助我。

+0

你需要另一個觸發AFTER'當一個新的捐助者進來時,INSERT'增加血液儲存量。 – Barmar

+0

這個事情可能是乞求一個交易包裝,因爲你正在更新手頭安息 – Drew

回答

0

我可以實現這個SQL服務器上,但我居然不知道該怎麼做MySQL的

我想有一個轉型可以實現手動

CREATE TRIGGER updatestock 
ON dbo.tab_m_donar 
AFTER INSERT, UPDATE, DELETE 
AS 

-- insert 
Update tab_t_bloodstock 
set bUnit = bUnit + i.bloodUnit 
from tab_t_bloodstock s 
inner join (
    select i.bgId, i.bloodUnit 
    from Inserted i 
    left join Deleted d on i.dId = d.dId 
    where d.dId is null 
) i on i.bgId = s.bgId 


-- update 
Update tab_t_bloodstock 
set bUnit = bUnit + u.ins - u.dels 
from tab_t_bloodstock s 
inner join (
    select i.bgId, i.bloodUnit ins, d.bloodUnit dels 
    from Inserted i 
    inner join Deleted d on i.dId = d.dId 
) u on u.bgId = s.bgId 



-- delete 
Update tab_t_bloodstock 
set bUnit = bUnit - d.bloodUnit 
from tab_t_bloodstock s 
inner join (
    select d.bgId, d.bloodUnit 
    from deleted d 
    left join inserted i on i.dId = d.dId 
    where i.dId is null 
) d on d.bgId = s.bgId 

go