简体   繁体   中英

Next Booking Record with Function and table

Now I am trying to find the next available booking for a patient with the help of UDF, as I am not sure I can do this in some other way.

This is my UDF:

CREATE FUNCTION [dbo].[fnGetNextBookingForPatient] 
     (@PatientId BIGINT,
      @BookingStartTime SMALLDATETIME)
RETURNS TABLE
AS
    RETURN 
        (SELECT TOP 1 
             BookingId As NextBookingId,
             C.Color As NextBookingCatColor,
             C.CategoryName As NextBookingCatName,
             b.StartTime As NextBookingTime
         FROM 
             dbo.Booking B
         INNER JOIN 
             Category C ON c.CategoryId = b.CategoryId
         WHERE 
             B.StartTime > @BookingStartTime
             AND b.PatientId = @PatientId
             AND ISNULL(B.IsCancelled, 0) = 0
             AND ISNULL(B.IsDeleted, 0) = 0
         ORDER BY 
             B.StartTime
    )

I need to get this next booking information for each record available in my temp table

Current temp table

PatientId| BookingId         |         BookingTime
---------+-------------------+---------------------
1235     | 15585             | 2017-02-19 08:00:00

Expected temp table

PatientId| BookingId |  BookingTime |     NextBookingId|  NextBookingTime
---------+-----------+--------------------+------------+-----------------
1235     | 15585     | 2017-02-19 08:00:00 | 16522      | 2017-02-23 11:00:00

This is what I tried

SELECT 
    *,
    dbo.fnGetNextBookingForPatient(PatientId, @TenantId, StartTime)
FROM 
    #Temp
ORDER BY 
    StartTime ASC

I am getting an error

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.fnGetNextBookingForPatient", or the name is ambiguous

As I am not familiar how to work with function returns multiple values I am stuck here.

What about using OUTER APPLY? Read here for more info on using this

    SELECT 
     T.*
        ,NB.NextBookingId
    FROM #Temp T
    OUTER APPLY 
    [dbo].fnGetNextBookingForPatient(t.PatientId, @TenantId, T.StartTime) NB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM