34,591
社区成员
发帖
与我相关
我的任务
分享
--游标
if object_id('tb') is not null
drop table tb
go
create table tb(name varchar(10),con int)
insert into tb select 'a',1
insert into tb select 'b',2
insert into tb select 'c',3
declare cursor_tb cursor for
select name ,con FROM tb
declare @name varchar(10),@con int
open cursor_tb--打开游标
fetch next from cursor_tb
into @name, @con
while @@FETCH_STATUS = 0 --取值正常的场合
begin
--sql
fetch next from cursor_tb
into @name, @con
end
close cursor_tb--关闭游标
deallocate cursor_tb--释放游标
--非游标方法
create table ta(userid int ,username varchar(10))
create table tb(userid int ,username varchar(10))
insert ta select 1,'A'
insert ta select 2,'B'
insert ta select 3,'C'
insert tb select 2,'D'
insert tb select * from ta a where not exists(select 1 from tb b where a.userid=b.userid)
select * from tb
drop table ta
drop table tb
userid username
----------- ----------
2 D
1 A
3 C
(3 行受影响)
--游标
if object_id('tb') is not null
drop table tb
go
create table tb(name varchar(10),con int)
insert into tb select 'a',1
insert into tb select 'b',2
insert into tb select 'c',3
declare cursor_tb cursor for
select name ,con FROM tb
declare @name varchar(10),@con int
open cursor_tb
fetch next from cursor_tb
into @name, @con
while @@FETCH_STATUS = 0
begin
select @name,@con--这里操作
fetch next from cursor_tb
into @name, @con
end
close cursor_tb
deallocate cursor_tb