我有一堆WITH
语句:
;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
我在
上加入这些陈述select * from myTable
join OneAccession
on...
join TwoACcessions
on...
join ThreeAccessions
我可以创建一个存储过程,而不是拥有所有那些with
语句吗?我只需传递having count(accession_id)=**@myParam**
的值并执行此操作:
select * from myTable
join storedproc(1)
on...
join storedproc(2)
on...
etc...
加入存储过程中是否存在问题?我的方法是否正常?
答案 0 :(得分:3)
看看APPLY
。将APPLY
与table-valued functions一起使用似乎是使用APPLY
的典型示例,我认为这就是您想要的。
使用示例(使用AdventureWorks)查看此blog post:
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'
答案 1 :(得分:1)
不......你可以使用表函数来代替。
答案 2 :(得分:1)
您可以不加入存储过程,但您可以加入函数和视图。请注意,视图不能采用参数,并且函数可能不如CTE那样高效。
另外,查看您的查询,看起来您应该查看新的窗口函数和
之类的内容;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
可能有助于实现您的目标。