DROP FUNCTION IF EXISTS fn_GetSchetSluchWPI;
CREATE FUNCTION fn_GetSchetSluchWPI
(
	"SchetUslID" uuid
)
RETURNS uuid AS
$BODY$	
Begin
	return
	(
		select wpi.WarrantyProgramItemID
		from AKUZ.T_SCHET_USL su
		inner join 
			AKUZ.T_SCHET_SLUCH ss 
			on ss.SchetSluchID = su.SchetSluch
		inner join 
			AKUZ.T_SCHET_ZAP sz 
			on sz.SchetZapID = ss.SchetZap
		inner join 
			AKUZ.T_SCHET s 
			on s.SchetID = sz.Schet
		inner join
			AKUZ.T_WARRANTY_PROGRAM_ITEM wpi
			on wpi.Code = su.CODE_USL
		inner join 
			AKUZ.T_WARRANTY_PROGRAM_GROUP wpg 
			on wpi.WarrantyProgramGroup = wpg.WarrantyProgramGroupID
			and wpg.WarrantyProgram = s.WarrantyProgram
		where su.SchetUslID = "SchetUslID"
		limit 1
	);
END $BODY$
  LANGUAGE plpgsql volatile
  COST 100;
ALTER FUNCTION fn_GetSchetSluchWPI(uuid)
  OWNER TO postgres;