现在就是有一批数据,然后循环着往表里面差,但是可能里面存在着这样的坏数据,就是主键重复的数据。
循环的过程中需要对这些数据不做处理。
也就是要判断下表中是否有了这个主键的数据。
比如:student表  
int id;   //主键
varchar name[20];
float score;如果有一条数据(5,'zhangsan',89.2);
那怎么来判断表中是否有了这个id=5的项呢?
用什么sql语句能解决。

解决方案 »

  1.   

    if exists(select * from student where id=5)
    print '存在'
    else
    print '不存在'
      

  2.   


    -----1
    create table #student
    (id int ,
    name varchar(20),
    score float )insert #student
    select 5,'zhangsan',89.2 union all
    select 6,'zhrtytry',56.5 union all
    select 7,'zhangsytry',78.6 union all
    select 8,'zhanrtyty',98.5-----------以上假如是楼主的旧数据------2  假设以下是楼主要插入#student的数据,如#tb中的数据插入到#student中,但已有的id不处理
    create table #tb
    (id int ,
    name varchar(20),
    score float )insert #tb
    select 1,'zhangsan1',89.2 union all
    select 2,'zhrtytry2',56.5 union all
    select 3,'zhangsytry3',78.6 union all
    select 4,'zhanrtyty4',98.5 union all
    select 5,'zhangsan5',89.2 union all
    select 6,'zhrtytry6',56.5 union all
    select 7,'zhangsytry7',78.6 -------以下是具体操作insert #student 
    select * from #tb as t where not exists(select 1 from #student as s where s.id=t.id)-----把#tb中id=1,2,3,4的记录插入了#student,因为5,6,7在#student已存在,所以没有处理。。