--if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_GetOmsPolicy]') and xtype in (N'FN', N'IF', N'TF'))
--drop function [dbo].[fn_GetOmsPolicy]
--GO

--create function [dbo].fn_GetOmsPolicy(@PatientID uniqueidentifier, @OnDate datetime)
--returns uniqueidentifier
--as
--begin
--	if @OnDate is null set @OnDate = getdate()
--	declare @policy uniqueidentifier
--			, @validThrough datetime
	
--	select top 1 @policy = PolicyID, @validThrough = ValidThrough from [AKUZ].T_POLICY with(nolock)
--	 where type_ = 536 and Patient = @PatientID and datediff(day, IssueDate, @OnDate) >= 0
--	 order by IssueDate desc, IsNull(ValidThrough,'20991231') desc
	 
--	if @validThrough is null or datediff(day, @validThrough, @OnDate) <= 0 
--	begin
--		return @policy
--	end
--	return null
--end	
--GO
