sql problem more difficult to appear in the forum: 44 (thematic call trigger data corresponding to the main table list insert data)

Original: SQL problem more difficult to appear in the forum: 44 (trigger thematic call list when inserting data corresponding to the main table data)

Recently, in the forum, I met a lot more difficult sql problem, although they can be resolved, but found a few days later, they can not remember, forget the solution of.

So, I feel the need to be recorded, so that after the encounter this problem again, and get answers from the idea.

In the flip-flop, the master table corresponding to a data call list when the data is inserted

http://bbs.csdn.net/topics/390631301

Hello everyone, as Kingdee ERP can not automatically calculated based on the number of spare spare rate quote inside. So it is necessary to build a trigger from.

My trigger is built on the list, call list when inserted into the corresponding data in the main table data, key data is then the main table did not seem committed to the database, is there any way to call, thank you.


my reply:

By the following experiment, verified, and if the transaction has not been submitted to the primary table, but want the main table with the corresponding data in the flip-flop, to calculate spare, is entirely possible.


Because the trigger is triggered and the operation, in the same transaction.
As long as you insert the main table, insert the list, in the same transaction, and it will also trigger the same transaction, although it did not submit the master table operation, but also in the query to trigger this has not master table records submitted.


   
   
  1. --主表
  2. create table t1
  3. (
  4. id int primary key,
  5. v varchar( 20)
  6. )
  7. --明细表
  8. create table t2
  9. (idd int primary key,
  10. id int references t1( id),
  11. vv varchar( 20)
  12. )
  13. insert into t1
  14. select 1, 'aa'
  15. insert into t2
  16. select 1, 1, 'xxx'
  17. union all select 2, 1, 'yyy'
  18. go
  19. create trigger dbo.trigger_t2
  20. on dbo.t2
  21. for insert
  22. as
  23. --查询主表t1,发现刚才插入数据的事务,虽然没有提交
  24. --但是在触发器中,完全可以查询到刚才插入到主表的数据
  25. select * from t1
  26. --下面可以引用t1表,也就是主表,和明细表,来计算出备品数
  27. go
  28. begin tran
  29. insert into t1
  30. select 2, 'bb'
  31. insert into t2
  32. select 3, 2, '123'
  33. --先不提交事务
  34. --commit
  35. /*
  36. id v
  37. 1 aa
  38. 2 bb
  39. */


Published 416 original articles · won praise 135 · views 950 000 +

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12020078.html