2017-04-11 63 views
0

表關係]刪除[1]如何從2個表使用SQL Server連接查詢

table **Student**

table **Student_Grade**

這裏是我的數據庫的截圖。

我想從Student表中刪除所有數據,使用Student_grade表,其中Grade='FAIL'

失敗學生的所有信息都應該從數據庫中刪除。

Delete from Student 
where Student_ID IN (Select Student_ID 
        from Student_Grade 
        where Grade = 'FAIL'); 

試過這個,但它不工作。我認爲數據應該一次從兩個表中刪除,因爲當它從一個Student表中刪除時,在student_grade表中沒有對FK的引用。

請任何人都可以提供SQL Server查詢來做到這一點?

+0

探索ON DELETE CASCADE:http://stackoverflow.com/questions/6260688/how-do-i-use-cascade-delete-with-sql-server –

+0

把TOP 1放在你選擇的位置,並將IN改爲= – CurseStacker

回答

1

我其實很喜歡松鼠的臨時做法(+1)。它允許一個更復雜的選擇標準。

也就是說,如果#TEMP表是「現成的表」,你可以做到以下幾點:

Delete A 
From Student A 
Join Student_grade B on (A.Student_ID=B.Student_ID) 
Where B.Grade='Fail'; 

Delete From Student_grade Where Grade='Fail'; 
2

您無法一次從2個表中刪除。

將studend_id的列表保存在臨時表中,然後使用它連接到實際表並一次刪除一個表。

-- put the list of Fail students in temp table #Fail 
Select Student_ID INTO #Fail from Student_Grade where Grade='FAIL' 

-- delete from grade table 
DELETE g FROM #Fail f INNER JOIN Student_Grade g ON f.Student_ID = g.Student_ID 

-- delete from student table 
DELETE s FROM #Fail f INNER JOIN Student s ON f.Student_ID = s.Student_ID 
0

有雙向做。

第一種方法,利用交易使用一個以上的DML

begin try 
begin tran 

-- Child table 
Delete From Student_grade Where Grade='Fail'; 

-- Parent table 
Delete A 
From Student A 
Join Student_grade B on (A.Student_ID=B.Student_ID) 
Where B.Grade='Fail'; 



commit TRAN 
end try 
begin catch 
if (@@Trancount>0) 
rollback 
end catch 

另一種方法是使用

刪除級聯

,如果你想刪除父表直時遠。 Delete data with foreign key in SQL Server table