请问不用游标,可否对记录集进行循环操作?

bleempan 2006-04-27 02:39:46
1.不用游标,可否对记录集行循环操作?

2.不用动态SQL语句可否根据参数创建不一样名字的游标.

declare @chvTemp varchar(10)
set @chvTemp = 'aaa'
declare @chvTemp cursor scroll for select intID from SalesManInfo

可是这样不行...

...全文
306 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
hyrongg 2006-04-27
  • 打赏
  • 举报
回复
不用游标循环的例子:

SET NOCOUNT ON
-- declare all variables!
DECLARE @iReturnCode int,
@iNextRowId int,
@iCurrentRowId int,
@iLoopControl int,
@vchCustomerName nvarchar(255),
@vchCustomerNmbr nvarchar(10)
@chProductNumber nchar(30)
-- Initialize variables!
SELECT @iLoopControl = 1
SELECT @iNextRowId = MIN(iRowId)
FROM CustomerTable
-- Make sure the table has data.
IF ISNULL(@iNextRowId,0) = 0
BEGIN
SELECT 'No data in found in table!'
RETURN
END
-- Retrieve the first row
SELECT @iCurrentRowId = iRowId,
@vchCustomerNmbr = vchCustomerNmbr,
@vchCustomerName = vchCustomerName
FROM CustomerTable
WHERE iRowId = @iNextRowId
-- start the main processing loop.
WHILE @iLoopControl = 1
BEGIN
-- This is where you perform your detailed row-by-row
-- processing.
-- Reset looping variables.
SELECT @iNextRowId = NULL
-- get the next iRowId
SELECT @iNextRowId = MIN(iRowId)
FROM CustomerTable
WHERE iRowId > @iCurrentRowId
-- did we get a valid next row id?
IF ISNULL(@iNextRowId,0) = 0
BEGIN
BREAK
END
-- get the next row.
SELECT @iCurrentRowId = iRowId,
@vchCustomerNmbr = vchCustomerNmbr,
@vchCustomerName = vchCustomerName
FROM CustomerTable
WHERE iRowId = @iNextRowId
END
RETURN
OracleRoob 2006-04-27
  • 打赏
  • 举报
回复

1、根据实际情况选择是否需要用游标

如表中有ID字段,且唯一,取@minID,@maxID,可以使用While循环
或者按日期,取最小日期、最大日期,日期递增1,也可以用while循环

declare @i int,@minID int,@maxID int

select @minID=min(id) from 表名
select @axID=max(id) from 表名

set @i=@minID

while @i<@maxID
begin
--...
update 表名 set ... where id=@id
--...

set @i=@i+1
end

2、必须使用动态SQL语句实现
btlyeo 2006-04-27
  • 打赏
  • 举报
回复
要不就把记录放到临时表里,创建临时表的时候指定一个自动增量的列,然后while循环操作,你不想用游标的原因是因为速度慢吧?

如果是这样可否考虑把数据量大的表里的查询结果(如果记录少)放到临时表里做,还有索引建全了没
OracleRoob 2006-04-27
  • 打赏
  • 举报
回复
1、根据实际情况选择是否需要用游标

如表中有ID字段,且唯一,取@minID,@maxID,可以使用While循环
或者按日期,取最小日期、最大日期,日期递增1,也可以用while循环

declare @i int,@minID int,@maxID int

select @minID=min(id) from 表名

set @i=@minID

while @i<@maxID
begin
--...
update 表名 where id=@id
--...

set @i=@i+1
end

2、必须使用动态SQL语句实现

bleempan 2006-04-27
  • 打赏
  • 举报
回复
楼上的朋友说的是前台的数据集吗?
我的想法是在存储过程中,查到记录以后直接循环对每条记录进行操作.
所有操作都在存储过程中进行的.
btlyeo 2006-04-27
  • 打赏
  • 举报
回复
在ASP上可以把记录集处理成数组,比如rs.GetRows()

网上资料很多
xeqtr1982 2006-04-27
  • 打赏
  • 举报
回复
2.

不用动态SQL肯定不行啊

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧