【问题标题】:Getting result of multiple SELECT statements from stored procedure从存储过程中获取多个 SELECT 语句的结果
【发布时间】:2013-06-19 18:07:07
【问题描述】:

我正在练习创建一个存储过程,其中包含多个 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。 请帮忙!

【问题讨论】:

    标签: sql sql-server stored-procedures


    【解决方案1】:

    您可以在每个SELECT 之间放置一个UNION

    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,你可能会得到重复,但查询会更快。

    【讨论】:

      【解决方案2】:

      将它们结合在一起

      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;
      

      【讨论】:

        猜你喜欢
        • 2017-02-21
        • 2014-08-02
        • 1970-01-01
        • 2017-04-21
        • 1970-01-01
        • 1970-01-01
        • 2018-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多