有部门表: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的记录,在删除前,要判断其他表是否有该条记录.应该怎么判断,
有很多表都有它.

解决方案 »

  1.   

    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,'彩电订单'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 行)
    */
      

  2.   

    所有的表都是用dept_id关联吗?
      

  3.   

    建立外键,
    这样判断最简单 
    if exists(select * from staff where dept_id=1)
    if exists(select * from order where dept_id=1)
      

  4.   

    是这样吗"
    @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
    大家帮我看看
      

  5.   

    这样就可以了,借用以下数据
    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