Question : Passing a string to a function

Can you pass a string to a function so it will be included in the WHERE clause of the function?


SELECT * FROM [fCaseLoadRU](1, 6, '7563-a', '  dc.DischargeDate IS NULL ')

Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
ALTER FUNCTION [dbo].[fCaseLoadRU](@agencyId bigint, @PersonnelId bigint = null, @ReportingUnit varchar(40) = null, @Filter varchar(200))
RETURNS TABLE
AS
RETURN (
		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)
			AND @Filter
			GROUP BY c.ID
		)a
)

Answer : Passing a string to a function

Yes. And this should work..
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
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;
Random Solutions  
 
programming4us programming4us