How to Update a Bridge Table Automatically

How to Update a Bridge Table Automatically

Case:

We have three tables:
1. Department
2. Stage
3. And a bridge table ' Dep_Stage

There is a need to automatically add new record to bridge table when ever a new record is added to Department.  Department and Stage both can join based on the OfficeID.


Department
DepID int Primary and Identity
DepName varchar(100) Checked
OfficeID int Checked

Stage
StageID int , PK and Identity
StageName varchar(50)
OfficeID int


DEP_Stage
DSID int Primary and Identity
DepID int  
OfficeID int  
StageID int  
DSNAME varchar(100)  


Solution:

Write a trigger in the Department table like this:

CREATE 

TRIGGER [dbo].[OnInsertNewRecord] ON [dbo].[Department]  
AFTER INSERT  AS
BEGIN
    SET NOCOUNT ON
    Declare @DepID as int 
       Declare @Office as Int 
    Declare @DSName as varchar(50
    select top 1  @DepID  = DepID, @DSNAme = DepName, @Office = OfficeID  from Inserted

 -- Insert statements for trigger here

     insert into Dep_Stage (DepID, StageID, OfficeID, DSName)  
    select @DepID, Stage.StageID, @Office, @DSName + '_' + StageName From Stage  where OfficeID =@Office 
 END

 

 

GO

Similarly we can add a trigger to the stage table as well. This will automatically fill the bridge table as and when the new record is added either to the Department or to the Stage table.


This can save time in maintaining the bridge or link tables in relational data models.

If you have any questions, please ask at sushil@grokinnovations.co.uk

Thanks,

Sushil Saini
www.grokinnovations.co.uk
Grok Innovations UK ltd.
Microsoft BI Stack Experts
Leave a Comment
  • Please add 3 and 4 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Comments
  • Ed Price - MSFT edited Revision 1. Comment: Title casing and minor edits.

Page 1 of 1 (1 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
  • Ed Price - MSFT edited Revision 1. Comment: Title casing and minor edits.

Page 1 of 1 (1 items)