从存储过程中获取多个SELECT语句的结果

时间:2013-06-19 10:02:55

标签: sql sql-server stored-procedures

我正在练习创建一个存储过程,其中包含多个select查询,我想将所有这些查询的结果作为一个数据集返回,以便将它们放入数组中。

但是根据我的编写,我的存储过程只返回第一个查询的结果,而不是其余的。

CREATE PROCEDURE getPost
AS
SET NOCOUNT ON
SELECT TOP 5 title,summary,cphoto,pId FROM [post] WHERE [status]=1 order by dtetme DESC;
SELECT TOP 1 title,summary,cphoto,pId FROM [post] WHERE [status]=1 order by dtetme DESC;
SELECT TOP 1 title,summary,cphoto,pId FROM [post] WHERE [status]=1 order by [hits] DESC;
SELECT TOP 5 title,summary,cphoto,pId FROM [post] WHERE [status]=1 AND category=(SELECT id FROM category where name='Small') order by dtetme DESC;
SELECT TOP 5 title,summary,cphoto,pId FROM [post] WHERE [status]=1 AND category=(SELECT id FROM category where name=’Medium’) order by dtetme DESC;
SELECT TOP 1 title,summary,cphoto,pId FROM [post] WHERE [status]=1 AND category=(SELECT id FROM category where name='Big’) order by dtetme DESC;
SELECT TOP 3 title,summary,cphoto,pId FROM [post] WHERE [status]=1 order by newid();
GO

我正在使用MS SQL Server。 请帮助!

2 个答案:

答案 0 :(得分:1)

将他们联合起来

SELECT TOP 5 title,summary,cphoto,pId FROM [post] WHERE [status]=1 
UNION ALL
SELECT TOP 1 title,summary,cphoto,pId FROM [post] WHERE [status]=1 
UNION ALL
...
order by title DESC;

答案 1 :(得分:1)

您可以在每个UNION

之间放置SELECT
CREATE PROCEDURE getPost
AS
SET NOCOUNT ON
SELECT TOP 5 title,summary,cphoto,pId FROM [post] WHERE [status]=1 order by dtetme     DESC
UNION
SELECT TOP 1 title,summary,cphoto,pId FROM [post] WHERE [status]=1 order by dtetme DESC
UNION
SELECT TOP 1 title,summary,cphoto,pId FROM [post] WHERE [status]=1 order by [hits] DESC
UNION
SELECT TOP 5 title,summary,cphoto,pId FROM [post] WHERE [status]=1 AND category=(SELECT id FROM category where name='Small') order by dtetme DESC
UNION
SELECT TOP 5 title,summary,cphoto,pId FROM [post] WHERE [status]=1 AND category=(SELECT id FROM category where name=’Medium’) order by dtetme DESC
UNION
SELECT TOP 1 title,summary,cphoto,pId FROM [post] WHERE [status]=1 AND category=(SELECT id FROM category where name='Big’) order by dtetme DESC
UNION
SELECT TOP 3 title,summary,cphoto,pId FROM [post] WHERE [status]=1 order by newid();
GO 

请注意,如果您使用UNION,则不会获得任何重复项,并且您的查询在大型数据集上可能会变慢。如果您使用UNION ALL代替,则可能会出现重复项,但查询速度会更快。