Cursor 的用法

 Cursor 的用法(一)

1 table1结构如下
 2 id    int
 3 name  varchar(50)
 4 
 5 declare @id int
 6 declare @name varchar(50)
 7 declare cursor1 cursor for         --定义游标cursor1
 8 select * from table1               --使用游标的对象(跟据需要填入select文)
 9 open cursor1                       --打开游标
10 
11 fetch next from cursor1 into @id,@name  --将游标向下移1行,获取的数据放入之前定义的变量@id,@name中
12 
13 while @@fetch_status=0           --判断是否成功获取数据
14 begin
15 update table1 set name=name+'1'
16 where id=@id                           --进行相应处理(跟据需要填入SQL文)
17 
18 fetch next from cursor1 into @id,@name  --将游标向下移1行
19 end
20 
21 close cursor1                   --关闭游标
22 deallocate cursor1 


--修改资有重名的数据(例二)


begin
declare @CustomerName nvarchar(100),
@rf_dept_ID nvarchar(100),
@CustomerType nvarchar(100),
@customerid int;
declare c_tex cursor for 
select CustomerName,rf_dept_ID,CustomerType d from res.dbo.cy_customers 
 where [Status]=1
 group by CustomerName,rf_dept_ID,CustomerType
 having count(1)>1 
 open c_tex
	fetch from c_tex into @CustomerName,@rf_dept_ID,@CustomerType
	while (@@FETCH_STATUS=0)
	begin
print @CustomerName+'---'+@rf_dept_ID+'---'+@CustomerType;
	select @customerid=min(customerid)  from res.dbo.cy_customers 
	where CustomerName=@CustomerName
	and rf_dept_ID=@rf_dept_ID
	and CustomerType=@CustomerType
	and [Status]=1;
		print @customerid;
		
update res.dbo.cy_customers set [Status]=0  
where CustomerName=@CustomerName
	and rf_dept_ID=@rf_dept_ID
	and CustomerType=@CustomerType and  
	customerid!=@customerid;
   --and [Status]!=1   ;

	fetch from c_tex into  @CustomerName,@rf_dept_ID,@CustomerType;
		end
		close c_tex;
		deallocate c_tex;
end;


游标一般格式:
DECLARE 游标名称 CURSOR FOR SELECT 字段1,字段2,字段3,... FROM 表名 WHERE ...
OPEN 游标名称
FETCH NEXT FROM 游标名称 INTO 变量名1,变量名2,变量名3,...
WHILE @@FETCH_STATUS=0
        BEGIN
                  SQL语句执行过程... ...
                  FETCH NEXT FROM 游标名称 INTO 变量名1,变量名2,变量名3,...
        END
CLOSE 游标名称
DEALLOCATE 游标名称 (删除游标)



(例三)

/*
功能:数据库表格tbl_users数据
deptid userid username
1          100      a
1      101      b
2      102      c
要求用一个sql语句输出下面结果
deptid username
1        ab
2        c
[要求用游标实现设计: OK_008
时间: 2006-05
备注:无
*/
create table #Temp1(deptid int,userid int,username varchar(20)) --待测试的数据表
create table #Temp2(deptid int,username varchar(20))                --结果表
--
先把一些待测试的数据插入到待测试表#Temp1中
insert into #Temp1
select 1,100,'a' union all
select 1,101,'b' union all
select 1,131,'d' union all
select 1,201,'f' union all
select 2,302,'c' union all 
select 2,202,'a' union all
select 2,221,'e' union all
select 3,102,'y' union all 
select 3,302,'e' union all
select 3,121,'t' 
--
declare @deptid int,@username varchar(20)
--定义游标
declare Select_cursor cursor for
        
select deptid,username from #Temp1
open Select_cursor
fetch next from Select_cursor into @deptid,@username    --提取操作的列数据放到局部变量中
while @@fetch_status=0      --返回被 FETCH 语句执行的最后游标的状态
/*

@@FETCH_STATUS =0          FETCH 语句成功
@@FETCH_STATUS =-1 FETCH 语句失败或此行不在结果集中
@@FETCH_STATUS =-2 被提取的行不存在
*/
        
begin
                  
--当表#Temp2列deptid存在相同的数据时,就直接在列username上追加@username值
                  if(exists(select * from #Temp2 where deptid=@deptid )) 
                          
update #Temp2 set username=username +@username where deptid=@deptid
                  
else 
                  
--插入新数据
                          insert into #Temp2 select @deptid,@username
                  
fetch next from Select_cursor into @deptid,@username
        
end
close Select_cursor      
deallocate Select_cursor
select * from #Temp2 --测试结果
Drop table #Temp1,#Temp2







游标(Cursor)主要用于数据库操作,是一种可以遍历查询结果集的对象。它允许逐行处理数据,并对每一行进行读取、修改等操作。以下是关于如何使用游标的详细介绍: ### 创建并打开游标 首先,在大多数SQL环境中,你需要声明一个游标并与特定的SELECT语句关联起来。 ```sql DECLARE my_cursor CURSOR FOR SELECT column_name(s) FROM table_name WHERE condition; OPEN my_cursor; -- 打开游标以便开始从中检索数据 ``` ### 获取数据 一旦打开了游标,就可以通过`FETCH`命令从当前记录指针的位置获取单条记录到变量中去。 ```sql FETCH NEXT FROM my_cursor INTO @variable_list; ``` 这里每次都会向前移动一行并且把值放入指定的目标变量里边。 ### 关闭及释放资源 完成所有需要的操作之后,应当记得关闭游标以节省系统资源以及解除锁定。 ```sql CLOSE my_cursor; DEALLOCATE my_cursor; ``` 这四个步骤构成了基本的游标工作流程:**声明->打开->提取(循环)->关闭&释放** --- 当涉及到实际的应用程序开发语言如Python连接MySQL时,则会有所区别: 对于Python而言,我们通常不会直接操作SQL中的游标语法,而是利用像PyMySQL这样的库提供的API来间接管理它们。下面给出一段简单的示例代码片段用于说明这一过程。 ```python import pymysql.cursors connection = pymysql.connect(host='localhost', user='root', password='', db='testdb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: sql_query = "SELECT `id`, `name` FROM `users`" cursor.execute(sql_query) # 遍历所有的返回结果 for row in cursor.fetchall(): print(f"ID={row['id']}, Name={row['name']}") finally: connection.close() ``` 此段脚本展示了怎样在一个安全的方式下建立同数据库间的链接、创建游标实例(`cursor`)、执行查询并将结果按字典形式返回供后续迭代打印出来;最后确保无论是否发生异常都能正常断开与DBMS之间的通信链路。 --
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值