【问题标题】:Stored procedure: return multiple columns instead of multiple recordsets?存储过程:返回多个列而不是多个记录集?
【发布时间】:2010-11-28 10:19:43
【问题描述】:

这可能是一个很简单的问题,但是我不经常写存储过程,有点迷茫……

在完成各种操作之后,SP 的结束位通过返回几个不同表的计数或总和来结束。显而易见的方法是:

select SUM(ThisCol) as ThisResult from...
select SUM(ThatCol) as ThatResult from...
select count(DISTINCT OtherCol) as OtherResult from...

当然,这会创建多个记录集 - 每个选择一个,一个包含零。这有点傻,因为每个记录集只包含一个值。我更愿意返回包含多个列的单个记录集:ThisResult、ThatResult 和 OtherResult。

这可能吗?

【问题讨论】:

  • 谢谢! najmeddine、Kane 和 David Andres 的回答都很好。我选择了带有变量的那个作为看起来最好的那个。

标签: sql stored-procedures


【解决方案1】:

你可以使用变量

DECLARE @thisResult INT
DECLARE @thatResult INT
DECLARE @otherResult INT

select @thisResult = SUM(ThisCol) as ThisResult from...
select @thatResult = SUM(ThatCol) as ThatResult from...
select  @otherResult = count(OtherCol) as OtherResult from...

SELECT  @thisResult AS 'thisResult', @thatResult AS 'thatResult', @otherResult AS 'otherResult'

【讨论】:

  • 我不得不从 select 语句中省略“as ThisResult”等 - 然后它正是我需要的 - 谢谢!
【解决方案2】:
SELECT T1.ThisResult, T2.ThatResult, T3.OtherResult
  FROM (select SUM(ThisCol) as ThisResult from...) T1,
       (select SUM(ThatCol) as ThatResult from...) T2,
       (select count(DISTINCT OtherCol) as OtherResult from...) T3

因为每个表只包含 1 个列和 1 个值,所以您对所有 3 个列进行交叉连接,并将每个值放入结果表的列中。

【讨论】:

    【解决方案3】:

    如果您使用的是 SQL Server,则可以再次选择这些数量作为最后一条语句。

    Select ThisResult, ThatResult, OtherResult
    

    您不必指定表格

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-04
      • 2013-09-01
      • 1970-01-01
      • 2021-04-21
      • 2015-05-29
      • 2017-05-06
      • 2011-04-22
      相关资源
      最近更新 更多