微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

插入数据,判断这条数据是否重复,游标中采用的思想是逐条循环判断是否添加
方法一:
insert into
dbo.News (NewsTitle,Typeid,TypeName,[content])
select NewsTitle,[content]
from dbo.News2 b
where b.NewsTitle not in(select  NewsTitle from dbo.News)

方法二:
insert into
dbo.News (NewsTitle,[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,[content])
    select NewsTitle,[content]
    from dbo.News2 where NewsId=@newsid
    end
fetch next from mycursor into @newsid,@newstitle
end

close mycursor
deallocate mycursor

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐