2017-02-19 1 views
1

Jetzt versuche ich mit Hilfe von UDF die nächste verfügbare Buchung für einen Patienten zu finden, da ich mir nicht sicher bin, ob ich das auf andere Weise machen kann.Nächster Buchungsrekord mit Funktion und Tabelle

Das ist mein 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 
    ) 

ich neben diesen Buchungsinformationen für jeden Datensatz in meiner temporären Tabelle

Aktuelle Temptabelle

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

Erwartete Temptabelle

erhalten müssen
PatientId| BookingId | BookingTime |  NextBookingId| NextBookingTime 
---------+-----------+--------------------+------------+----------------- 
1235  | 15585  | 2017-02-19 08:00:00 | 16522  | 2017-02-23 11:00:00 
Diese 363.210

ist, was ich versucht

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

I

eine Störung erhalte kann entweder Spalte „dbo“ oder die benutzerdefinierte Funktion oder Aggregat „dbo.fnGetNextBookingForPatient“ oder den Namen nicht finden mehrdeutig

Da ich nicht vertraut bin, wie man mit Funktion arbeitet, gibt mehrere Werte zurück Ich bin hier fest.

Antwort

2

Was ist mit OUTER APPLY? Lesen Sie here für weitere Informationen zur Verwendung dieser

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