sql游标使用的一个例子
程序员文章站
2024-02-10 14:30:16
...
这个是原生Sql使用游标对每次新加进来的一个区间判断是否与数据库中原有数据是否有重复的判断,最终输出1为无交集,输出0为有交集(不是指打印)。作为游标使用的一个例子。
--声明一个变量
declare @waterMin as numeric;
declare @waterMax as numeric;
--声明查询语句
DECLARE @sql AS varchar(4000);
SET @sql ='SELECT count(1) cout from ElectricScheme where AreaId=1 and Season=0 ';
--声明一个游标用来遍历查询到的结果
declare W_WaterMin CURSOR for select ElectricMin from ElectricScheme where AreaId=1 and Season=0 ;
declare W_WaterMax CURSOR for select ElectricMax from ElectricScheme where AreaId=1 and Season=0;
--打开游标
open W_WaterMin;
open W_WaterMax;
--获取游标指向的数据
fetch next from W_WaterMin into @waterMin;
fetch next from W_WaterMax into @waterMax;
--使用游标遍历集合
while @@FETCH_STATUS = 0
BEGIN
--执行具体的操作
--IF @waterMin!=0 AND @waterMax!=260
--BEGIN
SET @sql [email protected]+ ' and ( 260 < '+ cast(@waterMin as varchar(20));
SET @sql [email protected]+ ' or 0 > '+ cast(@waterMax as varchar(20)) +')';
--END
--游标指向下一条数据
FETCH next from W_WaterMin into @waterMin;
FETCH next from W_WaterMax into @waterMax;
END
--执行sql语句
print @sql;
SET @sql=' select COUNT(1) result from ( '[email protected]+' ) a inner join ( select COUNT(1) cout from ElectricScheme where AreaId=1 and Season=0 ) b on a.cout=b.cout '
print @sql;
EXEC(@sql);
--关闭游标
CLose W_WaterMin;
cLose W_WaterMax;
--释放游标
DEALLOCATE W_WaterMin;
DEALLOCATE W_WaterMax;