方法一:使用游标
declare @ProductName nvarchar(50) declare pcurr cursor for select ProductName from Products open pcurr fetch next from pcurr into @ProductName while (@@fetch_status = 0) begin print (@ProductName) fetch next from pcurr into @ProductName end close pcurr deallocate pcurr
此方法适用所有情况,对标结构没有特殊要求。
方法二:使用循环
declare @ProductName nvarchar(50) declare @ProductID int select @ProductID=min(ProductID) from Products while @ProductID is not null begin select @ProductName=ProductName from Products where ProductID=@ProductID print(@ProductName); select @ProductID=min(ProductID) from Products where ProductID>@ProductID end
此方法适用于表带有自动增加标识的字段
本文介绍两种在SQL中遍历表数据的方法:使用游标和使用循环。通过示例详细展示了如何定义和使用游标来逐条读取表中的记录,并提供了利用循环结构结合最小标识符进行数据迭代的实现方案。

被折叠的 条评论
为什么被折叠?



