i have list of records and have created cursor to loop through each record and check certain condition and return record if it satisfies my cursor is as follows :
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
in loop cursor fetch record whose id is '839' , Please help me solve the problem.
The FETCH statement advances the cursor to the first or next row in the set, and loads the values indicated in the SELECT clause of the DECLARE CURSOR statement into host language variables.
The FETCH statement retrieves rows of data from the result set of a multi-row query. You can fetch rows one at a time, several at a time, or all at once. The data is stored in variables or fields that correspond to the columns selected by the query.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With