存储过程:返回多列而不是多个记录集?

时间:2009-09-15 11:06:09

标签: sql stored-procedures

这可能是一个非常简单的问题,但我不经常编写存储过程而且我有点神秘......

在做了各种事情之后,SP的结束位通过返回来自几个不同表的计数或总和而结束。显而易见的方法是:

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

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

这可能吗?

3 个答案:

答案 0 :(得分:2)

您可以使用变量

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'

答案 1 :(得分:1)

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进行交叉连接,并将每个值放在结果表的一列中。

答案 2 :(得分:0)

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

Select ThisResult, ThatResult, OtherResult

您不必指定表