- 论坛徽章:
- 0
|
sql server中可以很容易的用游标实现循环,遍历表中记录;但游标在实际的开发中都不推荐使用。
我们知道还可以借助临时表或表变量等来实现循环
下例为用表变量来实现简单的循环:
(直接复制到查询分析器中运行即可)- declare @temp table
- (
- [id] int IDENTITY(1,1),
- [Name] varchar(10)
- )
- declare @tempId int,@tempName varchar(10)
- insert into @temp values(\'a\')
- insert into @temp values(\'b\')
- insert into @temp values(\'c\')
- insert into @temp values(\'d\')
- insert into @temp values(\'e\')
- --select * from @temp
- WHILE EXISTS(select [id] from @temp)
- begin
- SET ROWCOUNT 1
- select @tempId = [id],@tempName=[Name] from @temp
- SET ROWCOUNT 0
- delete from @temp where [id] = @tempId
- print \'Name:----\'+@tempName
- end
复制代码 |
|