使用求和查询和计数查询返回值

时间:2013-07-15 05:05:35

标签: sql variables select stored-procedures transactions

再次更新

我有2个表TestMain Id 名称)和Ref Id 名称 RefId ), TestMain的Id Ref的RefId 之间存在外键关系。这些是2个查询:

SELECT  T.Id, T.Name, COUNT(T.Name) AS COUNTNAME 
FROM TestMain AS T
INNER JOIN Ref AS T1
ON T.[Id] = T1.[RefId]
GROUP BY T.Name,T.Id
ORDER BY T.Id


SELECT SUM(COUNTNAME)
  FROM (
  SELECT  T.Id, COUNT(T.Name) AS COUNTNAME 
  FROM TestMain AS T
  INNER JOIN Ref AS T1
  ON T.[Id] = T1.[RefId]
  GROUP BY T.Name,T.Id
  ) AS SUMOFCOUNTNAME

我的存储过程在顶部使用2个查询来返回值:

CREATE PROCEDURE ReturnValues 
    @Name nvarchar(50) output,
    @Sum int output,
    @Count int output,
    @OutId int output 
AS
BEGIN
   SET XACT_ABORT ON
   BEGIN  TRAN 
    BEGIN TRY

      SELECT  @OutId = T.Id, @Name = T.Name, @Count = COUNT(T.Name) 
      FROM TestMain AS T
      INNER JOIN Ref AS T1
      ON T.[Id] = T1.[RefId]
      GROUP BY T.Name,T.Id
      ORDER BY T.Id

      SELECT @Sum = SUM(COUNTNAME)
      FROM (
        SELECT  T.Id, COUNT(T.Name) AS COUNTNAME 
        FROM TestMain AS T
        INNER JOIN Ref AS T1
        ON T.[Id] = T1.[RefId]
        GROUP BY T.Name,T.Id
        ) AS SUMOFCOUNTNAME

    COMMIT
    END TRY
    BEGIN CATCH
     ROLLBACK
    END CATCH
END

我的问题是如何只用一个查询返回变量:@Name@Sum@Count@OutId。我不想使用2个查询,我看起来非常糟糕。

这是TestMain的数据:

Id  Name
1   TestName1
2   TestName2
3   TestName3
4   TestName4
5   TestName5
6   TestName6
7   TestName7
8   TestName8
9   TestName9
10  TestName10

这是Ref的数据

Id  Name    RefId
1   TestRef1    1
2   TestRef2    2
3   TestRef3    2
4   TestRef4    3
5   TestRef5    3
6   TestRef6    3
7   TestRef7    4
8   TestRef8    4
9   TestRef9    4
10  TestRef10   4
11  TestRef11   5
12  TestRef12   5
13  TestRef13   5

我想获得@Sum但不要使用上一个查询。

0 个答案:

没有答案