0

我有一堆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...

加入存储的 Proc 是否有问题?我的方法可以吗?

4

3 回答 3

3

看看APPLY。使用APPLYwith表值函数似乎是 using 的经典示例APPLY,我认为这就是您想要的。

看看这个博客文章的例子(使用 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'
于 2012-10-18T22:26:08.553 回答
1

不...不过,您可以使用表函数来执行此操作。

于 2012-10-18T22:26:22.603 回答
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

可能对您想要实现的目标有所帮助。

于 2012-10-18T22:32:31.953 回答