再次更新
我有 2 个表TestMain
(Id,Name)和Ref
(Id,Name,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
但不使用最后一个查询。