create procedure [dbo].[pCaseLoadRU]
(@agencyId bigint, @PersonnelId bigint = null, @ReportingUnit varchar(40) = null, @Filter varchar(200))
AS
create table #temp ( ClientID int, ProviderNumber int, RUCount int);
declare @sql nvarchar(4000);
set @sql = '
SELECT ID as ClientID, ProviderNumber,
CASE WHEN a.RUCount = 1 THEN ProviderNumber ELSE ''YES: '' + CAST(a.RUCount AS VARCHAR(10))END as RUCount
FROM
( SELECT c.ID, RUCount= COUNT(*), ProviderNumber = MAX(e.ReportingUnit)
FROM Clients c
INNER JOIN Episodes e ON(c.ID = e.client_id)
LEFT JOIN ru repUnit ON(e.eRuId= repUnit.id)
INNER JOIN (SELECT * FROM UnitAllocation WHERE [PersonnelId] = @PersonnelId AND AccessToClientData =1) ua ON ReportingUnitID = repUnit.ID
LEFT JOIN (select * from fDischargeClientActive(@agencyId)) as dc ON (EpisodeID = e.episode_id)
WHERE c.agencyid = @agencyId
AND repUnit.reportingunit = ISNULL(@ReportingUnit, repUnit.reportingunit) '
+ (Select case when @Filter is not null then ' and ' + @Filter end)
+ ' GROUP BY c.ID )a )';
insert into #temp
exec sp_executesql @sql;
select * from #temp;
|