0

我正在练习创建一个包含多个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。请帮助!

4

2 回答 2

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;
于 2013-06-19T10:05:31.993 回答
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改用你可能会得到重复,但查询会更快。

于 2013-06-19T10:07:07.050 回答