Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have two tables as shown in below,

Table1
ID (INT, PK)
Param1 (NVARCHAR(50))

Table2
ID (INT, PK)
t1_ID (INT, FK)

Table1 is connected to Table2 via Table1.ID-Table2.t1_ID. And relationship has cascade at delete.

What I want to do is when user deletes a row in Table1 all associated rows in Table2 also deletes(which is why I open the cascade at delete), but I also want that when the rows deleting in Table2 get a Parameter at Table1.

How can I do that?

Thanks in advance.

I think I need to be more specific of what I'm trying to accomplish.

Think about 3 tables. Like this; Tables

When user deletes a payment in Payments table, the amounts in PaymentItems table associated with PaymentID will be added or substracted in Balance column in CompanyFinanceInformations table by PaymentType.

What I have tried:

SQL
CREATE TRIGGER DeleteTrigger
ON dbo.Table2
FOR DELETE
AS
BEGIN
     DECLARE @Param1 AS NVARCHAR(50)
     DECLARE @t1_ID AS INT
     SELECT @t1_ID = t1_ID FROM deleted
     SELECT @Param1 = Param1 FROM dbo.Table1 WHERE dbo.Table1.ID = @t1_ID
     -- In here @Param1 always returns NULL
END


I think about write a trigger for Table1, and in this trigger loop through all asscociated rows on Table2. But I have concerns about the performance and efficiency of this proccess.
Posted
Updated 12-Oct-17 2:35am
v4
Comments
Atlapure Ambrish 12-Oct-17 7:39am    
I am not sure, What you are trying to do in the trigger on Table2.

Also, if you write a trigger on Table1, you don't need to loop through the rows, you have t1_id (FK) in table2, so, you will be able to easily delete all the rows using this FK after you get ID in the trigger from deleted table.

DELETE FROM TABLE2
WHERE t1_ID = ID

1 solution

 
Share this answer
 
Comments
Onur ERYILMAZ 12-Oct-17 6:12am    
I have already cascade at delete option on. My problem is getting a column value from Table1 on deleting.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900