sql server 中怎么遍历数据表

zy41796745 2010-04-21 11:22:24
sql server 中怎么遍历数据表,就是一行一行的处理表中的数据.
...全文
120 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
快乐_石头 2010-04-21
  • 打赏
  • 举报
回复
從你的描述來看
是游標
但是看具體數據
或許不需要游標
zy41796745 2010-04-21
  • 打赏
  • 举报
回复
1、以下以SQL Server 2000中的NorthWind数据库中的Customers表为例,

用 临时表 + While循环 的方法, 对Customers表中的CompanyName列进行遍历



create table #temp
(
id int identity(1,1),
customer nvarchar(50)
)


declare @customer nvarchar(50)
declare @n int
declare @rows int

select @n=1

insert #temp(customer) select distinct companyname from customers

select @rows = @@rowcount



while @n <= @rows
begin


select @customer = companyname
from customers
where companyname=(select customer from #temp where id = @n)
order by companyname desc

print(@customer)

select @n = @n + 1

end


运行后, 输出结果如下:


(所影响的行数为 91 行)

Alfreds Futterkiste
Ana Trujillo Emparedados y helados
Antonio Moreno Taquería
Around the Horn
Berglunds snabbköp


htl258_Tony 2010-04-21
  • 打赏
  • 举报
回复
如果一定要用游标,参考SQL游标原理和使用方法
htl258_Tony 2010-04-21
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 happy_stone 的回复:]
從你的描述來看
是游標
但是看具體數據
或許不需要游標
[/Quote]。。
老黎 2010-04-21
  • 打赏
  • 举报
回复
[Quote=引用楼主 zy41796745 的回复:]
sql server 中怎么遍历数据表,就是一行一行的处理表中的数据.
[/Quote]
用游标,不过同1楼所说,很多需求看似需要用游标,但是可以不用游标来做
dawugui 2010-04-21
  • 打赏
  • 举报
回复
[Quote=引用楼主 zy41796745 的回复:]
sql server 中怎么遍历数据表,就是一行一行的处理表中的数据.
[/Quote]
--1.用游标.
游标的基本写法

declare @id int,@name varchar(20);
declare cur cursor fast_forward for
select id,name from a;
open cur;
fetch next from cur into @id,@name;
while @@fetch_status=0
begin
--做你要做的事
fetch next from cur into @id,@name;
end
close cur;
deallocate cur;


--2.用循环.

--假设ID从1开始连续并不间断.
declare @i as int
select @i = count(1) from tb
declare @j as int
set @j = 1
while @j <= @i
begin
...你的处理语句
set @i = @i + 1
end
shixixi1987 2010-04-21
  • 打赏
  • 举报
回复
使用游标

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧