2012-10-18 82 views
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... 

是否有加入对存储过程的问题?我的方法好吗?

回答

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 

可能与你想达到什么样的帮助。

+0

非常感谢你能告诉我如何select *,count(*)....等于有count ...? –

+0

添加了一些显示simularity的代码。正如其他人所指出的,TVF就是你所描述的内容,但考虑到你的代码,我会花一些时间看看是否没有其他方法。在不了解您的模式和数据的情况下,我当然不能肯定地说,但我认为您的方法不太可能是您尝试解决任何问题的最佳解决方案。 – jmoreno

+0

非常感谢我检查了这一点! –

3

看一看APPLY。使用APPLYtable-valued functions似乎是使用APPLY的经典示例,我认为这是您想要的。

看一看这个blog post用(使用的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' 
+0

谢谢!应用程序和存储过程之间有什么区别? –

+0

和你对这个解决方案有什么想法? http://stackoverflow.com/a/2563175/117700 –

+0

我认为正确的问题是''什么是TVF和存储过程之间的差异'',这是在这里回答:http://stackoverflow.com/questions/ 4254814/sql-server-table-valued -values-vs-stored-procedures – bhamby

1

不...你可以使用表函数虽然不是做到这一点。

+1

你能告诉我怎么样? –

+0

看到这篇文章:http://www.codeproject.com/Articles/167399/Using-Table-Valued-Functions-in-SQL-Server。一旦表函数被创建,你可以像使用连接/应用的表一样使用它。 – PseudoToad

+0

非常感谢! –

相关问题