利用游标循环:
DECLARE My_Cursor CURSOR --定义游标
FOR (SELECT * FROM dbo.Table) --查出需要的集合放到游标中
OPEN My_Cursor; --打开游标
FETCH NEXT FROM My_Cursor ; --读取第一行数据
WHILE @@FETCH_STATUS = 0
BEGIN
--UPDATE dbo.Table SET 字段1 =‘***’ WHERE CURRENT OF My_Cursor; --更新
--DELETE FROM dbo.Table WHERE CURRENT OF My_Cursor; --删除
FETCH NEXT FROM My_Cursor; --读取下一行数据
END
CLOSE My_Cursor; --关闭游标
DEALLOCATE My_Cursor; --释放游标
利用游标赋值循环:
declare @参数1 参数1类型,@参数2 参数2类型
DECLARE MyCursor CURSOR --定义游标(利用游标循环)
FOR (select 字段1,字段2 from Table) --查出需要的集合放到游标中
order by 字段1 --排序语句放在括号外
OPEN MyCursor; --打开游标
FETCH NEXT FROM MyCursor INTO @参数1 ,@参数2; --读取第一行数据
WHILE @@FETCH_STATUS = 0
Begin
if 条件成立
begin --如需跳过当前循环,需先赋值,再continue,否则会进入死循环
FETCH NEXT FROM MyCursor INTO @参数1 ,@参数2;
continue; --跳过当前循环,进入下一循环
end
if 条件成立
begin
Break; --跳出整个循环
end
--PRINT @参数1,参数2; --打印参数值(调试)
--UPDATE Table set 字段3=*,字段4=* where 字段1=@参数1 and 字段2=@参数2
--Insert into Table1(字段1,字段2) values(参数1,参数2)
--Delete from table where 字段1=参数1 and 字段2=参数2
FETCH NEXT FROM MyCursor INTO @参数1 ,@参数2; --赋值后进入下一循环
End
CLOSE MyCursor; --关闭游标
DEALLOCATE MyCursor; --释放游标
类似For循环的SQL循环:
declare @itemnumber int --定义需要循环的次数
declare @tagint int --定义标志字段,用于结束循环
set @tagint=1
select @itemnumber = count(distinct Creater) from Demo_TestTable where isnull(Creater,'')<>'' And
DATEDIFF(DAY,CreatDate,GETDATE())<1
if(@itemnumber>0)
begin
while @tagint<=@itemnumber
begin
waitfor delay '00:00:01' --每隔一秒再执行 可用参数变量替换
Update Demo_TestTable set CreatDate=GETDATE() where Creater =(
Select Creater from (
select Creater,ROW_NUMBER() over(order by Creater) as RowID from Demo_TestTable where
isnull(Creater,'')<>'' And DATEDIFF(DAY,CreatDate,GETDATE())<1 group by Creater
) TableA
where TableA.RowID=@tagint
)
set @tagint=@tagint+1
end
end