Reputation: 60741
I have a bunch of WITH
statements:
;with OneAccession as (
select client_id,COUNT(patient_id) PatientCount from
(
select client_id,patient_id
from F_ACCESSION_DAILY
group by CLIENT_ID,PATIENT_ID
having COUNT(ACCESSION_ID)=1
) a
group by CLIENT_ID
)
,
TwoAccessions as (
select client_id,COUNT(patient_id) PatientCount from
(
select client_id,patient_id
from F_ACCESSION_DAILY
group by CLIENT_ID,PATIENT_ID
having COUNT(ACCESSION_ID)=2
) a
group by client_id
)
,
ThreeAccessions as (
select client_id,COUNT(patient_id) PatientCount from
(
select client_id,patient_id
from F_ACCESSION_DAILY
group by CLIENT_ID,PATIENT_ID
having COUNT(ACCESSION_ID)=3
) a
group by client_id
)
etc
And I join these statements on
select * from myTable
join OneAccession
on...
join TwoACcessions
on...
join ThreeAccessions
Instead of having all those with
statements, can i just create a stored proc? I would just pass the value of having count(accession_id)=**@myParam**
and do this:
select * from myTable
join storedproc(1)
on...
join storedproc(2)
on...
etc...
Is there an issue on joining on a stored Proc? Is my methodology OK?
Upvotes: 0
Views: 367
Reputation: 13561
You can not join on a stored procedure, but you can join both a function and a view. Note that a view can not take parameters and that a function may not be as performant as the CTE.
Also, looking at your query, it looks like you should look into the new windowing functions and that something like
;with cte as (
select *, count(*) over (partition by client_id, patient_id) patientcount
from f_accession_daily
)
select * from myTable
inner join cte on ... and patientCount=1
might help with what you are trying to achieve.
Upvotes: 1
Reputation: 15450
Have a look at APPLY
. Using APPLY
with table-valued functions seems to be the classic example for using APPLY
, and I think it's what you want.
Have a look at this blog post with an example (using AdventureWorks):
select f.FirstName
,f.LastName
,f.JobTitle
,f.ContactType
,cc.CardNumber
from Sales.CreditCard cc
join Sales.ContactCreditCard ccc on cc.CreditCardID=ccc.CreditCardID
cross apply dbo.ufnGetContactInformation(ccc.ContactID) f
where cc.ExpYear=2008
and cc.ExpMonth=6
and cc.CardType='Vista'
Upvotes: 3