方法一:使用游标
- 代码
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 此方法适用于表带有自动增加标识的字段