IF object_id(N'fn_GetPaidServiceCurrentCost', N'FN') IS NOT NULL
    DROP FUNCTION [dbo].[fn_GetPaidServiceCurrentCost]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE function [dbo].[fn_GetPaidServiceCurrentCost] (@MedicalServiceID uniqueidentifier, @OnDate datetime, @CostCategory uniqueidentifier, @Lpu uniqueidentifier)
    returns decimal(12,2)
    as
    begin
	    declare @ret decimal(12,2), @Lpu1 uniqueidentifier, @Lpu2 uniqueidentifier, @rc int;
	    declare @Costs as table (id int identity, cost decimal(12, 2), LpuMain uniqueidentifier);

	    if @OnDate is null 
		    set @OnDate = getdate();
	
	    insert into @Costs(cost, LpuMain)
	        select top 2 psc.Cost, psc.LpuMain
	        from [AKUZ].T_PAID_SERVICE_COST psc with(nolock)
	        where psc.MedicalService = @MedicalServiceID
	            and datediff(day, psc.[Date], @OnDate) >= 0
	            and (psc.DateEnd >= @OnDate or psc.DateEnd is null)
	            and (psc.LpuMain = @Lpu or psc.LpuMain is null)
	            and psc.CostCategory = @CostCategory
	        order by psc.LpuMain desc, psc.[Date] desc;

	    set @rc = @@ROWCOUNT;

	    select @ret = c.cost, @lpu1 = c.LpuMain from @Costs c where c.id = 1;
	    select @lpu2 = c.LpuMain from @Costs c where c.id = 2;

	    if @rc = 0
		    return -1;

	    if @Lpu2 is not null or (@Lpu1 is null and @rc = 2)
		    return -2;

	    return @ret;
    end
GO


