ALTER FUNCTION [dbo].[DefaultSlaId](@iHdSectionId INT, @iPersonId INT) RETURNS INT AS BEGIN DECLARE @Result INT DECLARE @SlaRightsSectionId INT = (SELECT SlaRightsSectionId FROM tHdSection WHERE iHdSectionId = @iHdSectionId) SELECT TOP 1 @Result = Sla.iSlaId FROM tSla Sla INNER JOIN tSlaRights SlaRights ON Sla.iSlaId = SlaRights.liSlaRightsSlaId LEFT JOIN tRolePerson RolePerson ON RolePerson.liRolePersonRoleId = SlaRights.liSlaRightsRoleId WHERE SlaRights.bSlaRightsDefault = 1 AND (SlaRights.liHdSectionId = @SlaRightsSectionId OR SlaRights.liHdSectionId IS NULL) AND @iPersonId = ISNULL(SlaRights.liSlaRightsPersonId, RolePerson.liRolePersonPersonId) AND Sla.dSlaRemoved IS NULL ORDER BY nSlaQuality DESC IF @Result IS NULL SELECT TOP 1 @Result = iSlaId FROM tSla INNER JOIN vSlaAccess ON iSlaId = liSlaAccessSlaId WHERE liSlaAccessHdSectionId = @SlaRightsSectionId AND liSlaAccessPersonId = @iPersonId ORDER BY nSlaQuality ASC RETURN @Result END