views:

321

answers:

1

I have below trigger

ALTER TRIGGER [dbo].[DeleteUserData]
ON  [dbo].[site_users]
AFTER DELETE
AS 
BEGIN
SET NOCOUNT ON;

--delete user uploads
update my_gallery set deleted=1 where un=(select un from deleted) and subdomain=(select subdomain from deleted)

--delete user pms
delete from pms where toUn=(select un from deleted) and subdomain=(select subdomain from deleted)

--delete friends
delete from friend_blocked_list where  un=(select un from deleted) and subdomain=(select subdomain from deleted)

END

it works fine when i delete one user but if i delete more than one users subquery returns more than one user in deleted table and trigger fails.

how can i adjust it so that it works when i delete more than one user at a time?

I have thought about altering it as below. Is it correct way?

Altered

--delete user uploads
update my_gallery set deleted=1 where un in (select un from deleted) and subdomain in (select subdomain from deleted)

--delete user pms
delete from pms where toUn in (select un from deleted) and subdomain in (select subdomain from deleted)

--delete friends
delete from friend_blocked_list where  un in (select un from deleted) and subdomain in (select subdomain from deleted)

Some may ask why don't you add Foreign keys to tables but usernames unique within their subdomain

A: 

Yes, this is one way. It won't handle NULLs values in the sub queries though but I think this won't matter.

You can also use EXISTS (handles NULLs) and JOIN (an SO question on EXISTS/IN/JOIN)

Please note: SQL is designed to handle multiple rows anyway...

gbn