表A1
AutoID 班
1 1班
2 2班
3 3班
declare @num int
declare @i int
select @num=COUNT(AutoID) FROM [dbo].[A1]
set @i=0
while @i<@num
Begin
--通过循环取出班
set @i=@i+1
end
print @i
问题:怎么通过循环取出A1中的字段班的值
------解决方案--------------------
那就用游标操作
declare @class nvarchar(50)
declare cursor1 cursor for
select class from A1
open cursor1
fetch next from cursor1 into @class
while @@fetch_status=0
begin
print @class
fetch next from cursor1 into @class
end
close cursor1
deallocate cursor1
------解决方案--------------------
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-02-18 22:31:51
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (Intel X86)
-- Jun 17 2011 00:57:23
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[A1]
if object_id('[A1]') is not null drop table [A1]
go
create table [A1]([AutoID] int,[班] varchar(3))
insert [A1]
select 1,'1班' union all
select 2,'2班' union all
select 3,'3班'
--------------开始查询--------------------------
--select * from [A1]
declare @num int
declare @i int
select @num=COUNT(AutoID) FROM [dbo].[A1]
set @i=1
while @i<=@num
Begin
SELECT [班] FROM a1 WHERE autoid=@i
set @i=@i+1
end
print @i
----------------结果----------------------------
/*
(3 行受影响)
班
----
1班
(1 行受影响)
班
----
2班
(1 行受影响)
班
----
3班
(1 行受影响)
4
*/