fetch record from cursor in SQL
Replace your cursor with WHILE loops to gain faster performance as follows:
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
Since you have list of dates, you should declare the cursor for that list, not for tdp_ProviderAccomodationTariffPlan
:
CREATE TABLE #TEMP_TABLE (PATPID INT, RATE ..., STYPE ...)
DECLARE @MY_DATE DATETIME, @FromDate DATETIME, @ToDate DATETIME
SET @FromDate = '...'
SET @ToDate = '...'
DECLARE THE_CURSOR CURSOR FOR
select MY_DATE from YOUR_DATE_LIST
OPEN THE_CURSOR
FETCH NEXT FROM THE_CURSOR into @MY_DATE
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO #TEMP_TABLE
SELECT patpid,rate,SType FROM tdp_ProviderAccomodationTariffPlan
WHERE (@MY_DATE BETWEEN @FromDate AND @ToDate) and fk_patid = 162 and fk_pacid = 36
FETCH NEXT FROM THE_CURSOR into @MY_DATE
END
CLOSE THE_CURSOR
DEALLOCATE THE_CURSOR
select * from #temp_table
DROP TABLE #TEMP_TABLE
But I would recommend you to avoid of using cursors. It's easier and faster to do that in .NET code