将数据插入到一个表中,如果数据有重复自动跳过。如何实现?

Dugu_Niu 2003-12-12 10:23:52
我写了存储过程,用来把 TABLE1 和 TABLE2 两个表中的数据插入到temp表中
三个表的主键、索引都不相同

如果实现数据有重复(也就是违反了temp表中的主键约束)就自动跳过?
大虾帮忙!thanks

我的SQL语句如下:

INSERT INTO [temp]
(id, name, sex)
SELECT id, name, sex
FROM TABLE1

INSERT INTO [temp]
(id, name, sex)
SELECT id, name, sex
FROM TABLE2
...全文
135 14 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
xzx760815 2003-12-12
  • 打赏
  • 举报
回复
不好意思﹐剛才搞錯了﹗應該是﹕
insert [temp]
select id,name,sex from table1
where id not in(select id from temp)
or name not in(select name from temp)
or sex not in(select sex from temp)
union
select id,name,sex from table2
where id not in(select id from temp)
or name not in(select name from temp)
or sex not in(select sex from temp)
xzx760815 2003-12-12
  • 打赏
  • 举报
回复
insert [temp]
select id,name,sex from table1
where id,name,sex not in(select id,name,sex from temp)
union
select id,name,sex from table2
where id,name,sex not in(select id,name,sex from temp)

Dugu_Niu 2003-12-12
  • 打赏
  • 举报
回复
又试用了大力的
insert [temp]
select id,name,sex table1
union all
select id,name,sex table2
方法,还是不行
同上面的结果一样
victorycyz 2003-12-12
  • 打赏
  • 举报
回复
select id,name,sex into #t from table1
insert into #t select id,name,sex from table2

insert into [temp]
select distinct a.*
from #t a left join [temp] b
on a.id=b.id and a.name=b.name and a.sex=b.sex
where b.id is null

drop table #t
Dugu_Niu 2003-12-12
  • 打赏
  • 举报
回复
我用了(马甲)的方法,
没有成功,他还是提示 违反了temp表中的主键约束 ,没有实现自动跳过
wzh1512 2003-12-12
  • 打赏
  • 举报
回复
不好意思,上面的写漏了:
insert into [temp]
select id,name,sex from table1
union
select id,name,sex from table2
Dugu_Niu 2003-12-12
  • 打赏
  • 举报
回复
在我的Temp表中id,name,sex都是索引
pengdali 2003-12-12
  • 打赏
  • 举报
回复
insert temp
select * from (
select id,name,sex table1
union
select id,name,sex table2)
where id not in (select id from temp)
pengdali 2003-12-12
  • 打赏
  • 举报
回复
insert [temp]
select id,name,sex table1
union all
select id,name,sex table2
wzh1512 2003-12-12
  • 打赏
  • 举报
回复
如果table1中没有重复记录,table2中也没有重得记录,也可以用:
insert into [temp]
select * from
(
select id,name,sex table1
union
select id,name,sex table2
) tep

wzh1512 2003-12-12
  • 打赏
  • 举报
回复
insert into [temp]
select distinct * from
(
select id,name,sex table1
union
select id,name,sex table2
) tep
txlicenhe 2003-12-12
  • 打赏
  • 举报
回复
INSERT INTO [temp]
(id, name, sex)
SELECT id, name, sex
FROM TABLE1
where id not in (select id from [temp])

INSERT INTO [temp]
(id, name, sex)
SELECT id, name, sex
FROM TABLE2
where id not in (select id from [temp])

xzx760815 2003-12-12
  • 打赏
  • 举报
回复
pengdali那個有學問題﹕
既然id,name,sex三個為主鍵值﹐那如果只是id相同那不一定就是相同的記錄﹗﹗﹗﹗﹗﹗
所以應該是id,mname,sex都相同才表示是相同記錄﹗﹗﹗
ghosthjt 2003-12-12
  • 打赏
  • 举报
回复
where 判断复重字段 not in(select 判断复重字段 from table)

34,838

社区成员

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

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