在发一贴,咨询insert项时对主键值是否重复的问题

zhouliang0806 2011-05-12 08:19:16
现在就是有一批数据,然后循环着往表里面差,但是可能里面存在着这样的坏数据,就是主键重复的数据。
循环的过程中需要对这些数据不做处理。
也就是要判断下表中是否有了这个主键的数据。
比如:student表
int id; //主键
varchar name[20];
float score;

如果有一条数据(5,'zhangsan',89.2);
那怎么来判断表中是否有了这个id=5的项呢?
用什么sql语句能解决。
...全文
45 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhouliang0806 2011-05-12
  • 打赏
  • 举报
回复
给力,结贴
liang145 2011-05-12
  • 打赏
  • 举报
回复

-----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已存在,所以没有处理。。
叶子 2011-05-12
  • 打赏
  • 举报
回复
if exists(select * from student where id=5)
print '存在'
else
print '不存在'

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧