有部门表:dept
dept_id dept_name
1 市场部
2 开发部
有员工表:staff
staff_id dept_id staff_name
1 1 小张
有订单表:order
order_id dept_id order_name
1 1 彩电订单
--------------------------------
现在我要删除部门表中dept_id=1的记录,在删除前,要判断其他表是否有该条记录.应该怎么判断,
有很多表都有它.
dept_id dept_name
1 市场部
2 开发部
有员工表:staff
staff_id dept_id staff_name
1 1 小张
有订单表:order
order_id dept_id order_name
1 1 彩电订单
--------------------------------
现在我要删除部门表中dept_id=1的记录,在删除前,要判断其他表是否有该条记录.应该怎么判断,
有很多表都有它.
解决方案 »
- 关于sql server2000的时间的一个问题,帮忙看看
- 请问怎样管理放在异地服务器上的 SQL Server ?(急!在线等)
- 对不起啊 刚才的问题可能没问清楚 两个一起结贴吧
- 精度中使用变量
- 连接数据库出现错误
- sql语句求助:上周三12点之后到本周三12点之前
- 关于时间的处理
- 不知道java application(使用jbuilder)里面如何连接SQL Server2000数据库?
- 如何通过触发器,当新增、修改、删除中,把A数据库表a的字段a1、a2自动加入到数据库B表a的字段a1、a2?
- 两个相同结构的表A和B,怎样写这个SQL删除语句
- 如何得到下属部门的员工?
- 大家帮我看看这个是怎么回事?
insert @a
select '市场部'
union all
select '开发部'
declare @b table(staff_id int,dept_id int,staff_name varchar(20) )
insert @b
select 1,1,'小张'
declare @c table(order_id int,dept_id int,order_name varchar(20))
insert @c
select 1,1,'彩电订单'delete from @a where dept_id not in (
select a.dept_id from @a a,@b b,@c c where charindex(cast(a.dept_id as varchar),cast(b.dept_id as varchar))>0 and charindex(cast(a.dept_id as varchar),cast(c.dept_id as varchar))>0
)select * from @a
/*(所影响的行数为 2 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)dept_id dept_name
----------- --------------------
1 市场部(所影响的行数为 1 行)
*/
这样判断最简单
if exists(select * from staff where dept_id=1)
if exists(select * from order where dept_id=1)
@dept_id int
AS
if exists(select * from staff where dept_id=dept_id)
if exists(select * from order where dept_id=dept_id)
DELETE FROM dept WHERE dept_id=@dept_id
大家帮我看看
declare @a table(dept_id int identity(1,1),dept_name varchar(20))
insert @a
select '市场部 '
union all
select '开发部 '
declare @b table(staff_id int,dept_id int,staff_name varchar(20) )
insert @b
select 1,1, '小张 '
declare @c table(order_id int,dept_id int,order_name varchar(20))
insert @c
select 1,1, '彩电订单 '
----测试一,可删除
--if not exists(select * from @b where dept_id=2)
--if not exists(select * from @c where dept_id=2)
--DELETE FROM @a WHERE dept_id=2
--测试二,不可删除
if not exists(select * from @b where dept_id=1)
if not exists(select * from @c where dept_id=1)
DELETE FROM @a WHERE dept_id=1select * from @a
select * from @b
select * from @c