--年级与学校
alter table 年级 add constraint FK_年级_学校 foreign key(xxdm) references 学校(xxdm)--班级与年级
alter table 班级 add constraint FK_班级_年级 foreign key(njbj) references 学校(njbj)--班级与学校
alter table 班级 add constraint FK_班级_学校 foreign key(xxdm) references 学校(xxdm)

解决方案 »

  1.   

    --不对,按楼主的表设计,因为年级表中,njbh不是主键/唯一键,所以无法用外键约束建立班级与年级之间的年级编号约束.--需要用触发器来实现,即应该是这样:--年级与学校
    alter table 年级 add constraint FK_年级_学校 foreign key(xxdm) references 学校(xxdm)
    go--班级与年级(因为年级的bjbh不是主键/唯一键,所以得用触发器)
    create trigger tr_constraing on 年级
    for update,delete
    as
    if exists(select 1 from 班级 a,deleted b where a.njbh=b.njbh)
        rollback tran
    go--班级与学校
    alter table 班级 add constraint FK_班级_学校 foreign key(xxdm) references 学校(xxdm)
      

  2.   

    触发器应该还要修改一点。
    --班级与年级(因为年级的bjbh不是主键/唯一键,所以得用触发器)
    create trigger tr_constraing on 年级
    for update,delete
    as
    if exists(select 1 from 班级 a,deleted b where a.xxdm=b.xxdm and a.njbh=b.njbh )
        rollback tran
    go
    对了,我如何返回信息给用户-报错信息?
      

  3.   

    create trigger tr_constraing on 年级
    for update,delete
    as
    if exists(select 1 from 班级 a,deleted b where a.xxdm=b.xxdm and a.njbh=b.njbh )
    begin
        raiserror('要删除的年级已经有班级引用,不能删除',1,16)
        rollback tran
    end
    go
      

  4.   

    1.在Sql Server中会的到Raiserror的错误消息,但是在web应用程序如何得到?
    2.还有,比如说我同时删除4条记录,但是只有两条能够删除,另外两条不能删除,
    那如何知道到底是那两条不能删除?
      

  5.   

    我现在建立这个触发器后。进行删除操作,try{
        删除操作
    }
    catch(SqlException exp)
    {
     例外处理}
    现在我得删除操作在try语句块里成功退出,而没有我理解的那样进入catch操作,就没有办法进行catch处理。
      

  6.   

    --1.程序中用错误处理肯定是可以得到 raiserror 的错误的--2.如果要得到那些记录违反规则,导致不能删除,改触发器如下
    create trigger tr_constraing on 年级
    for update,delete
    as
    declare @s varchar(8000)
    set @s=''
    select @s=@s+','+cast(a.xxdm as varchar)+'--'+cast(a.njbh as varchar)
    from 班级 a,deleted b 
    where a.xxdm=b.xxdm and a.njbh=b.njbh 
    if @@rowcount>0
    begin
    set @s=stuff(@s,1,1,'')
        raiserror('下级年级已经被引用:
    %s
    不能删除',1,16,@s)
        rollback tran
    end
    go