sqlserver常用操作——判断关键字段是否重复插入记录

sqlserver常用操作(2)——判断关键字段是否重复插入记录
插入数据,判断这条数据是否重复,游标中采用的思想是逐条循环判断是否添加。
方法一:
insert into
dbo.News (NewsTitle,Typeid,TypeName,[content])
select NewsTitle,Typeid,TypeName,[content]
from dbo.News2 b
where b.NewsTitle not in(select  NewsTitle from dbo.News)

方法二:
insert into
dbo.News (NewsTitle,Typeid,TypeName,[content])
select NewsTitle,Typeid,TypeName,[content]
from dbo.News2 b
where not exists
(select * from dbo.news where NewsTitle=b.NewsTitle)

游标操作示例一:
declare   @cur_pos   int  
declare   mycursor   cursor   for   select   NewsTitle,Typeid   from   dbo.News  
declare   @col1   char(10)  
declare   @col2   char(10)    
open   mycursor  
fetch next from mycursor   into   @col1,@col2  
while   @@fetch_status<>-1  
begin  
print @col1+@col2
--select   @cur_pos=@cur_pos+1  
fetch next from  mycursor   into   @col1,@col2  
end  
close mycursor
deallocate mycursor

游标操作示例二:
declare @cur_pos int
declare @newsid int
declare @newstitle varchar(20)
declare mycursor cursor for select Newsid,NewsTitle from dbo.News2

open mycursor
fetch next from mycursor into @newsid,@newstitle
while @@fetch_status<>-1
begin
if not exists
(select * from dbo.News where NewsTitle=@newstitle)
    begin
    insert into dbo.News(NewsTitle,Typeid,TypeName,[content])
    select NewsTitle,Typeid,TypeName,[content]
    from dbo.News2 where NewsId=@newsid
    end
fetch next from mycursor into @newsid,@newstitle
end

close mycursor
deallocate mycursor
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值