SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[MEDWEB_DRRANDEVUGUN]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.MEDWEB_DRRANDEVUGUN
GO

CREATE FUNCTION dbo.MEDWEB_DRRANDEVUGUN  
(
    @SUBEID int,
    @DRID int,
    @TARIH smalldatetime
)
RETURNS @retRANDSAAT TABLE 
(
	SAAT smalldatetime
) 
AS
BEGIN
	DECLARE 
	  @RBASSAAT smalldatetime,
	  @RBITISSAAT smalldatetime,
	  @MAXRANDEVUGUNSAYI int,
	  @RANDEVUSONTARIH datetime
	  
	SELECT @MAXRANDEVUGUNSAYI = WEBMAXRANDEVUGUNSAYI, @RANDEVUSONTARIH = RANDEVUSONTARIH FROM TDRKIMLIK WHERE DRID = @DRID
	
	IF (@MAXRANDEVUGUNSAYI IS NOT NULL AND @TARIH > DATEADD(DAY,ISNULL(@MAXRANDEVUGUNSAYI,0),dbo.TARIHAL(GETDATE()))) OR
	   (@RANDEVUSONTARIH IS NOT NULL AND @TARIH > @RANDEVUSONTARIH)
	    RETURN
	ELSE
	BEGIN  
	    SELECT @RBASSAAT = RANDBASSAAT, @RBITISSAAT = RANDBITISSAAT FROM SUBELER WHERE SUBEID = @SUBEID
	    IF @TARIH = CAST(@RANDEVUSONTARIH AS DATE) AND CAST(@RANDEVUSONTARIH AS TIME) < CAST(@RBITISSAAT AS TIME) 
	      SET @RBITISSAAT = CAST(CAST(@RANDEVUSONTARIH AS TIME) AS DATETIME)
        --PRINT 'RBASSAT: ' + cast(@RBASSAAT as nvarchar(50)) + ' RBITISSAAT: ' + cast(@RBITISSAAT as nvarchar(50))
        INSERT @retRANDSAAT (SAAT)
	    SELECT SAAT
	    FROM dbo.RANDEVUGUN (@DRID, @TARIH, default)
	    WHERE RANDEVUID IS NULL AND HASTA IS NULL AND IZINLI = 0 AND 
	          CAST(SAAT AS datetime) >= @RBASSAAT AND 
		      CAST(SAAT AS datetime) < @RBITISSAAT 			
    END
    RETURN
END
GO
