IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FNMED_DOKTOR_RANDEVULAR]') AND xtype in (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].[FNMED_DOKTOR_RANDEVULAR]
GO
	CREATE FUNCTION [dbo].[FNMED_DOKTOR_RANDEVULAR]
	(@DRID INT, @OFFSET INT, @ROWNUM INT, @BASTARIH DATETIME, @BITTARIH DATETIME,@ADISOYADI NVARCHAR(50), @HTCKIMLIKNO NVARCHAR(50))

	RETURNS TABLE
	RETURN
	SELECT R.RANDEVUID, ISNULL(H.HKIMLIKID,0) AS HKIMLIKID, R.ADISOYADI AS HADISOYADI, R.RTARIH, R.RSAAT, R.RSURE, ISNULL(H.HTCKIMLIKNO,'') AS HTCKIMLIKNO
	FROM HRANDEVU R  WITH(NOLOCK)
	LEFT JOIN HKIMLIK H WITH(NOLOCK) ON H.HKIMLIKID=R.KIMLIKID
	WHERE R.DRID=ISNULL(@DRID,0)
	AND
	(@BASTARIH IS NULL OR R.RTARIH >= @BASTARIH)
	AND
	(@BITTARIH IS NULL OR R.RTARIH < @BITTARIH + 1)
	AND
	(ISNULL(@ADISOYADI,'')='' OR R.RADI +' ' + R.RSOYAD LIKE @ADISOYADI + '%')
	AND 
	(ISNULL(@HTCKIMLIKNO,'')='' OR R.RTCKIMLIKNO LIKE @HTCKIMLIKNO + '%')
	ORDER BY R.RTARIH ASC, R.RSAAT ASC
	OFFSET @OFFSET ROWS
	FETCH NEXT @ROWNUM ROWS ONLY
GO
IF EXISTS (SELECT [name] FROM [sys].[database_principals] WHERE [type] = N'S' AND [name] = N'mediwebuser')
BEGIN
	BEGIN TRY
		GRANT EXECUTE ON [dbo].[FNMED_DOKTOR_RANDEVULAR] TO [mediwebuser]
	END TRY
	BEGIN CATCH
	END CATCH
END
GO
