Avatar of ol muser
ol muser
Flag for United States of America asked on

cusrosr vs subquery

Hi, Is there a way to use a sub query or a combination of select+delete statements to accomplish what the cursor does?

In short I need to be able to select for evey patient that is in the patientdetails table details of the labwork that satisfy certain conditions as below.

    declare cur_patients cursor
        for select patientid, notepadid, lastdocumented, currenthospdate,  MostRecentDischDate
        from patiendetails
    open cur_patients
    fetch cur_patients into @pid, @npid, @LDdate, @CHdate, @MRDdate
    while (@@fetch_status <> -1)
    begin
        select @startdate = dateadd(dd, -180, getdate())
        if (@LDdate < @startdate)
           select @startdate = @LDdate
        select @undocenddate = getdate()
        if (@CHdate != NULL)
        begin
            select @undocenddate = @CHdate  
        end
        select @undocstartdate = @LDdate
        if (@MRDdate != NULL AND @MRDdate > @LDDate)
        begin
            select @undocstartdate = dateadd(dd, 1, @MRDdate)
        end
       
       
        insert tempdb..ptlabs
        select distinct
            teo.PatientId
            ,teo.OrderDate
            ,teo.OrderResultValue
            ,teo.ChecklistTestCode
            ,teo.OrderName
            ,teo.OrderResultNonMayoLab
            ,teo.LastChangedDate
        from labresults teo
        where patientid = @pid
            and completed = 'y'
            and @startdate <= LastChangedDate
            and LastChangedDate <= getdate()    
            and @undocstartdate <= lastchangeddate
            and lastchangeddate <= @undocenddate
           
        fetch next from cur_patients into @pid, @npid, @LDdate, @CHdate, @MRDdate
    end
    close cur_patients
Sybase Database

Avatar of undefined
Last Comment
Joe Woodhouse

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Joe Woodhouse

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck