给你一个例子 和说明 我看来几遍就学会游标了 下面是例子
---------------------------------------------------------------------
定义游标
Declare MyCursor Cursor For
Select Field1,Field2
From MyTable
Where (Field1 Like '%123%') And (Field2 = 'qqq') And (Field3 Is Not Null) And ......
Group By Field1,Field2
For Read Only
Open MyCursor
移动游标
fetch first from 游标 into 变量列表
取下一条
fetch next from 游标 into 变量列表
取第n条
fetch absolute n from 游标 into 变量列表
例子
日前,因工作需要累加某表里面的某字段的全部值,
比如有个表,内容如下
id,text
1,春花秋月何时了
2,往事知多少
3,小楼昨夜又春风
4,古国不堪回首月明中
......
其中id为系列号,text为文本内容,我想使用个sql语句,达到如下效果:
查询text列,查询的值累加,即查询结果显示如下:
春花秋月何时了 往事知多少 小楼昨夜又春风 古国不堪回首月明中 ...
用存储过程+游标实现,示例如下
ALTER PROCEDURE [dbo].[abc]
-- Add the parameters for the stored procedure here
@p1 int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @ttt varchar(100);
declare @bbb varchar(10);
set @ttt=''
set @bbb=''
declare mycur cursor for
select meno from test where gid= @p1
open mycur
fetch next from mycur into @bbb
WHILE @@FETCH_STATUS = 0
BEGIN
set @ttt=@ttt+@bbb
fetch next from mycur into @bbb
end
close mycur
select @ttt
---------------------------------------------------------------------
定义游标
Declare MyCursor Cursor For
Select Field1,Field2
From MyTable
Where (Field1 Like '%123%') And (Field2 = 'qqq') And (Field3 Is Not Null) And ......
Group By Field1,Field2
For Read Only
Open MyCursor
移动游标
fetch first from 游标 into 变量列表
取下一条
fetch next from 游标 into 变量列表
取第n条
fetch absolute n from 游标 into 变量列表
例子
日前,因工作需要累加某表里面的某字段的全部值,
比如有个表,内容如下
id,text
1,春花秋月何时了
2,往事知多少
3,小楼昨夜又春风
4,古国不堪回首月明中
......
其中id为系列号,text为文本内容,我想使用个sql语句,达到如下效果:
查询text列,查询的值累加,即查询结果显示如下:
春花秋月何时了 往事知多少 小楼昨夜又春风 古国不堪回首月明中 ...
用存储过程+游标实现,示例如下
ALTER PROCEDURE [dbo].[abc]
-- Add the parameters for the stored procedure here
@p1 int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @ttt varchar(100);
declare @bbb varchar(10);
set @ttt=''
set @bbb=''
declare mycur cursor for
select meno from test where gid= @p1
open mycur
fetch next from mycur into @bbb
WHILE @@FETCH_STATUS = 0
BEGIN
set @ttt=@ttt+@bbb
fetch next from mycur into @bbb
end
close mycur
select @ttt