Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 how to write the trigger for this?

Author  Topic 

allan8964
Posting Yak Master

249 Posts

Posted - 2012-03-05 : 13:48:54
Hi there,

Table1
tb1Id | Name

Table2
tb2Id | tb1Id | tb3Id

Table3
tb3Id | Code | Name (same as Name in Table1)

Now the requirement is when a new item added or deleted from Table3 a new item will be added or removed from Table2 as following:

Table1
11 | ABC

Table2
23 | 11 | 34

Table3
34 | T35 | ABC (same as that in Table1)

I know how to add a new item to Table3 and update Table2. But I don't know how to update Table2 when I delete from Table3. Here are codes I update Table2 on adding in Table3.

declare @tb1Id int, @tb3Id int, @Name varchar(10);
insert into Table3(Code, Name) Values('T35', 'ABC')
set @tb3Id = (select Max(tb3Id) from Table3)
set @Name = (select Name from Table1 where tb3Id = @tb3Id)
set @tb1Id = (select tb1Id from Table1 t1
inner join Table3 t2 on t1.Name = t2.Name
where t2.Name = @Name
group by tb1Id)
insert into Table3(tb1Id, tb3Id) Values(@tb1Id, @tb3Id)

Thanks in advance.

X002548
Not Just a Number

15586 Posts

Posted - 2012-03-05 : 13:52:28
what if the table3ID is NOT in Table 2?

What you need to do is to enforce RI



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page

allan8964
Posting Yak Master

249 Posts

Posted - 2012-03-05 : 14:06:23
Tb3Id must be in Table2. This is required from the beginning.
Thanks.
Go to Top of Page
   

- Advertisement -