T-SQL循环创建记录集

时间:2009-06-24 22:12:08

标签: sql tsql cursors

我有一些存储过程需要针对讨厌的数据库野兽编写。我需要使用应用程序表中的application_id循环遍历表(应用程序)并从其他表中提取值(一些是aggerate / averages / etc值)。

到目前为止,我有:

declare @id INT
declare app cursor for
    SELECT application_id from application
OPEN app
FETCH NEXT FROM app 
INTO @id
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT a.NAME_LAST, a.NAME_FIRST, ca.status, (SELECT AVG(score) FROM reviews WHERE application_id = @id), (SELECT count(*) FROM reviews WHERE application_id = @id)  FROM application a, committee_applications ca WHERE a.application_id = ca.application_id AND a.application_id = @id
  FETCH NEXT FROM app INTO @id
END
CLOSE app
DEALLOCATE app

这给了我想要的结果,但我确信有一种更清洁的方法可以做到这一点,而今天我似乎无法做出正确的跳跃来正确地做到这一点。有人可以指出一个更好的方法,因为这对我来说真的很难看。

此外,似乎我应该将这些值存储到临时表中,然后返回完整的结果,而不是逐个运行SELECT语句。

任何建议都将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:2)

删除光标可能会加快速度。通过使用派生表,您可以使用一个查询获取计数和平均值,并将其连接回其他表以获取其余列。像这样....

SELECT a.NAME_LAST, 
       a.NAME_FIRST, 
       ca.status, 
       Scores.AverageScore,
       Scores.CountScore
FROM   application a
       Inner Join committee_applications ca 
         On a.application_id = ca.application_id
       Left Join (
         SELECT application_id, 
                AVG(score) As AverageScore, 
                Count(*) As CountScore
         FROM   reviews 
         Group By application_id
         ) As Scores
         On a.application_id = Scores.application_id