SQL游标的简单使用
---声明游标
DECLARE mc CURSOR FOR
SELECT *
FROM t1
--定义变量
declare @oldtime varchar(30), @newtime int ,@temp varchar(40)
--打开游标
OPEN mc
--在游标中取出一条数据
FETCH NEXT FROM mc
INTO @oldtime, @newtime
--开始用 while 循环来 从游标中获取数据
WHILE @@FETCH_STATUS = 0
BEGIN
if(left(@oldtime,4) is not null)
BEGIN
if(len(@oldtime)=7)
begin
SET @temp =left(@oldtime,4)
set @newtime =cast(@temp+'0'+substring(@oldtime,6,1) as int)
print @newtime
update t1 set m1=@newtime where m= @oldtime
end
else
begin
SET @temp =left(@oldtime,4)
set @newtime =cast(@temp+''+substring(@oldtime,6,2) as int)
print @newtime
update t1 set m1=@newtime where m= @oldtime
end
end
--在从游标中取出一条数据,可以用next之类的方法
FETCH NEXT FROM mc
INTO @oldtime, @newtime
END
--循环结束
CLOSE mc
--关闭游标同时删除游标
DEALLOCATE mc
说明:其实游标还有许多方法 @@FETCH_STATUS = 0 游标的状态。
还有mc 是 声明的游标还有许多的方法。