T-SQL 循环创建记录集
我有一些存储过程需要针对令人讨厌的数据库野兽编写。 我需要循环遍历一个表(应用程序)并使用应用程序表中的 application_id 从其他表中提取值(有些是合计/平均值/等值)。
到目前为止,我已经:
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 语句。
任何建议将不胜感激。
谢谢。
I have some stored procedures that I need to write against a nasty beast of an database. I need to loop through a table (application) and pull values out of other tables (some are aggerate / averages /etc values) using the application_id from the application table.
So far I have:
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
Which is giving me the results I want, but I'm sure there is a cleaner way of doing this, and I can't seem to make the mental jump today to do this correctly. Could someone point out a better way of doing this as this seems really ugly to me.
Also, it seems like I should be storing these values into a temp table then returning the full results instead of running the SELECT statement one by one.
Any suggestions would be greatly appreciated.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
删除光标可能会大大加快速度。 通过使用派生表,您可以通过一个查询获取计数和平均值,并将其连接回其他表以获取剩余的列。 像这样....
Removing the cursor will probably speed this up a lot. By using a derived table, you can get the counts and averages with one query and join that back to the other tables to get the remaining columns. Like this....