SQL - 在触发器中连接表

时间:2014-10-31 20:28:10

标签: sql sql-server

我正在使用SQL服务器,我想要做的是创建一个触发器,每当ShipDate(来自表" OrderHeader&#)时,将QtyOnHand(从表" book")减1 34;)从NULL更新为实际日期。

从下表中可以看出,OrderHeader和Book并不直接相关,我必须通过OrderHeader的OrderDetail表来获取书籍的ISBN,然后从具有相应ISBN的Book表中减少QtyOnHand

我尝试连接触发器中的所有3个表来比较OrderNo,ISBN和QtyOnHand以进行比较,但我不确定这是否是解决此问题的正确方法。

任何建议将不胜感激。谢谢

OrderHeader

+-----------+---------+------+-----+
| Name      | Type    | Null | Key |   
+-----------+---------+------+-----+
| OrderNo   | int     | NO   | PRI |
| MemberID  | char(10)| NO   |     |    
| OrderDate | date    | NO   |     |
| Address   | char(30)| NO   |     |
| ShipDate  | date    | YES  |     |
+-----------+---------+------+-----+

的OrderDetail

+-----------+---------+------+-----+
| Name      | Type    | Null | Key |   
+-----------+---------+------+-----+
| OrderNo   | int     | NO   | PRI |
| OrderLine | int     | NO   | PRI |    
| ISBN      | char(10)| NO   |     |
| Quantity  | int     | NO   |     |
| Price     | decimal | NO   |     |
+-----------+---------+------+-----+

+-----------+---------+------+-----+
| Name      | Type    | Null | Key |   
+-----------+---------+------+-----+
| ISBN      | char(10)| NO   | PRI |
| Author    | char(50)| NO   |     |    
| Title     | char(80)| NO   |     |
| QtyOnHand | int     | NO   |     |
| Price     | decimal | YES  |     |
+-----------+---------+------+-----+

1 个答案:

答案 0 :(得分:0)

我会这样做,没有运行查询可能会有一些语法错误,

MERGE Book As Target
USING (Select OH.ISBN FROM OrderHeader OH
Inner join OrderDetail OD 
ON OH.OrderNo  = OD.OrderNo 
Where OD.ShipDate  IS NOT NULL ) AS Source
ON Source.ISBN = Target.ISBN
WHEN MATCHED THEN
  UPDATE
  SET Target.QtyOnHand  = Target.QtyOnHand  + 1;