34,576
社区成员
发帖
与我相关
我的任务
分享
DELETE 另一个表 FROM 学生表 where 另一个表.学生ID=学生表.学生ID and 学生表.所在班级='01'
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2011-04-15 14:56:49
-- Verstion:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Evaluation Edition on Windows NT 5.1 <X86> (Build 2600: Service Pack 3)
--
----------------------------------------------------------------
--> 测试数据:[ta]
if object_id('[ta]') is not null drop table [ta]
go
create table [ta]([学生ID] int,[所在班级] int)
insert [ta]
select 1,1 union all
select 2,1 union all
select 3,2
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([PK] int,[学生ID] int)
insert [tb]
select 1,1 union all
select 2,2 union all
select 3,3
--------------开始查询--------------------------
delete b from tb b join ta a on a.学生ID=b.学生ID where a.所在班级=1
select * from tb
----------------结果----------------------------
/* PK 学生ID
----------- -----------
3 3
(1 行受影响)
*/
declare @学生表 table (学生ID int,所在班级 int)
insert into @学生表
select 1,1 union all
select 2,1 union all
select 3,2
declare @另一个表 table (PK int,学生ID int)
insert into @另一个表
select 1,1 union all
select 2,2 union all
select 3,3
delete @另一个表 from @另一个表 a
left join @学生表 b on a.学生ID=b.学生ID where b.所在班级=1
select * from @另一个表
/*
PK 学生ID
----------- -----------
3 3
*/
delete b from tb b join ta a on a.学生ID=b.学生ID where a.所在班级=1
delete a from 另一个表 a where exists(select 1 from 学生表 where 所在班级=1 and 学生ID=a.学生ID)