标签:while core ast and pen open code exe 结果
---恢复内容开始---
游标:游标是一种能从包含多个数据的结果集每次提取一条的机制
游标的特点是:
为何使用游标:
游标的步骤
代码详解:
1. 定义游标
DECLARE 游标名 [ INSENSITIVE ] [ SCROLL ] CURSOR FOR T-SQL 语句
2. 打开游标
OPEN 游标名
3. 使用游标
FETCH [ NEXT | PRIOR | FIRST | LAST | ABSOLUTE { n | @nvar } | RELATIVE { n | @nvar } ] FROM 游标名
into 给局部变量赋值
ps 只有在定义游标时设置为SCROLL , 才可使用除 NEXT 其他标签
4. 关闭游标
CLOSE 游标名
5. 删除游标
DEALLOCATE 游标名
示例:
前提: 表 stuscore
表内数据:
目的: 将表改成如图形式
代码
/*定义局部变量,用于存储sql语句*/
declare @sql varchar(max) set @sql=‘select distinct( sname )‘ /*定义游标使用的的局部变量*/ declare @cname varchar(20) /*定义游标*/ declare cur_stuscore cursor read_only for select distinct(cname) from stuscore /*打开游标*/ open cur_stuscore /*使用游标*/ fetch next from cur_stuscore into @cname /*使用while循环,使语句遍历整表*/ while(@@FETCH_STATUS=0) begin set @sql=@sql+‘,(select s.score from stuscore s where s.cname=‘‘‘+@cname+‘‘‘ and s.sname=t.sname)as ‘‘‘+@cname+‘‘‘‘ fetch next from cur_stuscore into @cname end /*更新SQL语句*/ set @sql=@sql+‘ from stuscore t‘ /*执行SQL语句*/ exec (@sql) /*关闭游标*/ close cur_stuscore /*删除游标*/ deallocate cur_stuscore
ps: SQL执行语句为:
select distinct( sname ),
(select s.score from stuscore s where s.cname=‘语文‘ and s.sname = t.sname) as ‘语文‘,
(select s.score from stuscore s where s.cname=‘数学‘ and s.sname = t.sname) as ‘数学‘,
(select s.score from stuscore s where s.cname=‘英语‘ and s.sname = t.sname) as ‘英语‘
from stuscore t
标签:while core ast and pen open code exe 结果
原文地址:http://www.cnblogs.com/ang-664455/p/7096717.html