如何使用SQL Server

时间:2017-04-11 02:47:24

标签: sql-server join using

[表关系] [1]

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查询来执行此操作吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我其实喜欢Squirrel的临时演习(+1)。它允许更复杂的选择标准。

那就是说,如果#temp表是#34; off-the-table",你可以这样做:

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 :(得分: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

相关问题