从SQL中的游标获取记录

Dha*_*tel 6 cursor sql-server-2008

我有记录列表并创建了游标循环遍历每个记录并检查某些条件并返回记录,如果它满足我的光标如下:

DECLARE @ID int
DECLARE @FromDate datetime, @ToDate datetime
DEClare @expid as int
set @expid = 839
DECLARE IDs CURSOR FOR 
select patpid,fromdate,todate from tdp_ProviderAccomodationTariffPlan where fk_patid =    162 and fk_pacid = 36

 OPEN IDs
 FETCH NEXT FROM IDs into @ID,@FromDate,@ToDate
 WHILE @@FETCH_STATUS = 0
 BEGIN
print @ID 
print @FromDate
print @ToDate

--SELECT patpid,rate,SType FROM tdp_ProviderAccomodationTariffPlan 
--WHERE ('2012-12-27' BETWEEN @FromDate AND @ToDate) and fk_patid = 162 and fk_pacid = 36

FETCH NEXT FROM IDs into @ID,@FromDate,@ToDate  

END
CLOSE IDs
DEALLOCATE IDs
Run Code Online (Sandbox Code Playgroud)

在循环游标中获取id为'839'的记录,请帮我解决问题.

Zoo*_*ooZ 6

用WHILE循环替换光标以获得更快的性能,如下所示:

select identity(int,1,1) as id, patpid,fromdate,todate
INTO #temp1
from tdp_ProviderAccomodationTariffPlan
where fk_patid =    162 and fk_pacid = 36

declare @index int
declare @count int

select @count = count(*) from @temp1
set @index = 1

declare @patpid int
declare @fromdate datetime
declare @todate datetime

while @index <= @count
begin

  select @patid = patid,
         @fromdate = fromdate,
         @todate = todate
  from #temp1
  where id = @index

  -- do your logic here

  set @index= @index + 1
end

drop table #temp1
Run Code Online (Sandbox Code Playgroud)