有学生信息表student,属性编号、姓名、性别、分数,其中编号是标识列自动生成。现要创建一存储过程完成插入学生信息数据的功能,该过程执行一次插入一条学生信息,若如下编写此存储过程
create proc pr_insert_student
@姓名 varchar(20),
@性别 varchar(10),
@分数 numeric(10,2)=0
as
insert student(姓名,性别,分数) values(@姓名,@性别,@分数)
go
会发生这样的情况,若表里已经有学生张东,男,80;现又插入同一人张东,男,80,由于编号是自动生成,可以执行,这样的错误如何避免?请大虾指点,不胜感谢!

解决方案 »

  1.   

    建议学生信息表和分数表最好分为两个表判断是否学生信息重复取决于判定条件,例如以学生姓名和性别同时相符来判定该学生重复,存储过程可以更改如下:
    create proc pr_insert_student
    @姓名 varchar(20),
    @性别 varchar(10),
    @分数 numeric(10,2)=0
    as
      if(exists(select * from student where 姓名=@姓名 and 性别=@性别))
        return -1
      insert student(姓名,性别,分数) values(@姓名,@性别,@分数)
    go
      

  2.   

    insert into  student (姓名,性别,分数) select top 1 @姓名,@性别,@分数 from student
    where not exists (select 1 from student where  姓名=@姓名 and 性别=@性别 and 分数=@分数)
    -----或者
    if not exists(select * from student where  姓名=@姓名 and 性别=@性别 and 分数=@分数)
      insert student(姓名,性别,分数) values(@姓名,@性别,@分数)
      

  3.   


    create proc pr_insert_student
    @姓名 varchar(20),
    @性别 varchar(10),
    @分数 numeric(10,2)=0
    as
    Begin 
      If eists(Select 1 from student where name = @姓名) 
        BEGIN
         Raiserror('这个学生已经存在!',16, 1 )
         Return -1
        End
      
       insert student(姓名,性别,分数) values(@姓名,@性别,@分数)End