日期:2014-05-18  浏览次数:20357 次

不显示删除回复显示所有回复显示星级回复显示得分回复 求SQL语句:存在就跳过,不存在就插入记录,从字段ID=1开始,到字段ID=1某个值结束?
如题:我现在有一张表,其中里面有字段为HangNo,字段类型为int,我想通过一条SQL语句来实现:循环插入记录操作,让记录的HangNo=1插入到HangNo=n,其中n大于或等于1,如果在表中已经存在HangNo等于要插入的值,则跳过该记录
表中可能存在这些情况:
1,表中一条记录都没有,HangNo字段从1到n,插入n条记录;
2. 表中有一些记录,如果存在HangNo字段值等于要插入的值,则跳过该记录,不存在则插入该记录。
3. 表中存在HangNo字段从1到n的记录,甚至HangNo字段的记录个数超出n条,实际并不会插入任何记录。
这个SQL循环插入不存在的记录的语句该怎么写?最好能MySQL和SQL SERVER中都支持该语法
希望是一条组合起了的SQL语句,以便我能直接作为MFC程序的SQL字符参数,而不是在MySQL中写存储过程

------解决方案--------------------
假如你的1到N在某个表tb1,要插入表tb2

insert into tb2 select ... from tb1 where not exists(select 1 from tb2 where tb2.关键字 = tb1.关键字)
------解决方案--------------------
declare @i int
set @i = 1;
while (1=1)
begin
if @i =n
bein
break;
end
if not exists(select * from T where HangNO = @i)
begin
insert into T (HangNo) values (@i);
end 
@i = @i + 1;
end
------解决方案--------------------
假如你的1到N在某个表tb1,要插入表tb2

insert into tb2 select ... from tb1 where not exists(select 1 from tb2 where tb2.关键字 = tb1.关键字) 
 
如果不存在表tb1,则可以使用系统表sysobjects来生成你的序列表.
select (select count(1) from sysobjects m where m.id < n.id) + 1 as px from sysobjects n
------解决方案--------------------
SQL code
insert into tb  select HangNo from tb1 where not exitsts (select HangNo  from tb2 where tb.关键字 = tb1.关键字)
这是从一个表中复制到tb表中字段HangNo