开发者

Delete with inner join across 3 tables

I have three tables one of this storing users basic information, the other one is profile information and the last one is storing user picture.

When i deleting these user i need to delete all of the data in these tables. So i write a query like this.

DELETE Kullanicilar FROM Kullanicilar 
INNER JOIN ProfilBilgileri ON Kullanicilar.ID = ProfilBilgileri.UyeID 
INNER JOIN UyeResim ON Kullanicilar.ID = UyeResim.UyeID 
WHERE Kullanicilar.ID=@ID

But it just deleting the data from "Kullanicilar" table开发者_运维知识库.

Any suggestions?

EDIT : I'm using MSSQL 2008 but hosting firm 2000 so i need compatible code.


You can use a trigger like Xavinou sugested or, if you have foreign keys in your tables, you can go with Delete on Cascade option. Your foreign keys will be created using this:

FOREIGN KEY ([Id]) REFERENCES AnotherTable
ON DELETE CASCADE


The solution that springs to mind is to use a transaction.

BEGIN TRANSACTION

DELETE FROM Kullanicilar WHERE ID = @ID
DELETE FROM ProfilBilgileri WHERE UyeID = @ID
DELETE FROM UyeResim WHERE UyeID = @ID

COMMIT TRANSACTION


declare @pbid int
declare @urid int    
SELECT @pbid = ProfilBilgileri.UyeID, @urid = UyeResim.UyeID FROM Kullanicilar INNER JOIN ProfilBilgileri ON Kullanicilar.ID = ProfilBilgileri.UyeID INNER JOIN UyeResim ON Kullanicilar.ID = UyeResim.UyeID WHERE Kullanicilar.ID=@ID

delete Kullanicilar where ID = @ID
delete ProfilBilgileri where UyeID = @pbid
delete UyeResim where UyeID = @urid

Of course, I'm assuming that there's a 1-to-1 correspondence between Kullanicilar and the other two tables. If it's 1-to-many, you'll need a temp table for each of the other tables and delete based on that. Hope this points you in the right direction!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜