
正文
sqlserver存储过程while sqlserver存储过程for循环
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
SQLserver中存储过程中如何循环取值
sqlserver 中循环取值有两种方法:
1.使用游标
2.mssql sqlserver 遍历循环的新方法-使用while语句+临时表的方法。
相关问答
Q1: SqlServer存储过程
create procedure prCreateSubPlan
as
begin
declare @id int,
@intCycle int,
@planName varchar(100),
@createTime smalldatetime,
@cycleTime int
select @id = min(t_cplan_id) from t_cplan
while (@id is not null)
begin
select @planName=t_plan_name, @createTime = createTime, @cycleTime = cycleTime from t_cplan where t_cplan_id=@id
select @intCycle= 0
while (@intCycle@cycleTime)
begin
-- 表t_plan 列t_plan_id是IDENTITY 列
insert t_plan (t_plan_name, t_cplan_id, createTime)
values (@planName, @id, dateadd(day, @intCycle, @createTime))
select @intCycle = @intCycle + 1
end
select @id = min(t_cplan_id) from t_cplan where t_cplan_id@id
end
end
go
Q2: sqlserver存储过程何循环读表。
使用游标,如下
CREATE PROCEDURE proc_getalltable
AS
BEGIN
SET NOCOUNT ON;
DECLARE @tablename VARCHAR(100),@sql VARCHAR(1000)
DECLARE tablename CURSOR FOR SELECT tname FROM tablelist
OPEN tablename
FETCH NEXT FROM tablename INTO @tablename
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @sql = 'SELECT * FROM ' + @tablename
EXEC(@sql)
FETCH NEXT FROM tablename INTO @tablename
END
CLOSE tablename
DEALLOCATE tablename
END
GO
Q3: Sqlserver存储过程如何写循环
declare @i int
set @i = 0
while @i 100
begin
print @i
set @i = @i + 1
end
-- 定义循环变量
declare @loopIndex int set @loopIndex = 0
--定义循环次数
declare @count int set @count=1
-- 取得循环次数
select @count=count(1) from sys_user
-- 开始循环
while @loopIndex = @count
begin
-- 定义接收参数
declare @USER_NAME nvarchar(50)
-- 取得循环的数据
SELECT @USER_NAME = hh.USER_NAME
FROM (SELECT ROW_NUMBER() OVER (ORDER BY USER_NAME) 'rowindex',USER_NAME FROM sys_user)hh
WHERE hh.rowindex = @loopIndex
-- 进行相关业务逻辑 例如输出结果
print @USER_NAME
-- 循环自动加一
set @loopIndex = @loopIndex + 1
end
begin
-- 定义错误返回信息
declare @error int
-- 定义接收参数
declare @User_Name varchar(50)
declare @Address varchar(50)
set @error=0
--定义游标
declare demo_cursor cursor
for (select User_Name,Address from sys_user)
--打开游标--
open demo_cursor
--开始循环游标变量--
fetch next from demo_cursor into @User_Name,@Address
while @@FETCH_STATUS = 0 --返回被 FETCH语句执行的最后游标的状态--
begin
print @User_Name+'____'+@Address
set @error= @error + @@ERROR --记录每次运行sql后是否正确,0正确
fetch next from demo_cursor into @User_Name,@Address --转到下一个游标,没有会死循环
end
close demo_cursor --关闭游标
deallocate demo_cursor --释放游标
end
更多内容请访问:
Q4: sqlserver 存储过程中循环遍历结果集
sql1=select * from (select *, row_number() over(order by username ) as rowNumber from users where regfrom='admin') as t where t.rowNumber 0 and t.rowNumber = 0 + 30 order by username
怎么会有27 条记录呢,除非你的表 一共就27条记录吧。
用游标或临时表
--游标
declare youbiao1 for 查询1
open youbiao1
fetch next from youbiao1 into 变量
while @@FETCH_STATUS = 0
begin
里面一次套用
end
--临时表
declare @ID int
set @ID = 1
while Exists(select * from 表)
begin
--处理
--
set @ID = @ID + 1
end
sqlserver存储过程while的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于sqlserver存储过程for循环、sqlserver存储过程while的信息别忘了在本站进行查找喔。








