SQL Server trigger insert values from new row into another table with many-to-many relationship

情到浓时终转凉″ 提交于 2019-12-11 08:17:16

问题


I have three tables:

  • tbl_profiles
  • tbl_options
  • tbl_profileOption

with many-to-many relationship

what the insert trigger on tbl_options I have to use to add the new options to each profile on tbl_profiles, by default value of isChoose is 0

and on the opposite side when insert a new profile binding it with all options on tbl_options

In other words :

If I add new Option (4....E) to tbl_option, the trigger must be insert two new rows on tbl_profileOption:

1....4.......0
2....4.......0

I hope that my question is clear,


回答1:


thank for all who try to help me... I got the solution

  • first trigger on tbl_option

    go
    Create TRIGGER insertProfileToOption
    ON dbo.tbl_options
    AFTER INSERT
    AS
    insert into tbl_profileOption (profileOption_profileId,
      profileOption_optoinId)
    (select tbl_profiles.profile_id, @@IDENTITY from tbl_profiles)
    
  • second trigger on tbl_profile

    go
    Create TRIGGER insertOptionToProfile
    ON dbo.tbl_profiles
    AFTER INSERT
    AS
    insert into tbl_profileOption (profileOption_profileId,
      profileOption_optoinId)
    (select @@IDENTITY, tbl_options.option_id from tbl_options)
    

if there is another solution this will be good, thank you



来源:https://stackoverflow.com/questions/16246697/sql-server-trigger-insert-values-from-new-row-into-another-table-with-many-to-ma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!