将 SQL SP 结果分配给变量并对结果求和

Assign SQL SP Result to Variables and Sum Result

问题:两个存储过程 return 一个 int 值,但两个 int 值的总和 returns 默认为 0

我已经看到了各种选择的解决方案,这些解决方案可以工作或使用临时 table 没问题,但我需要单独保存结果,然后在最后对它们求和。(允许 sp 是模块化的) 保持 2008 兼容性的任何想法?

主要思想是让一个父 sp 有一个总结果和几个模块化的子 sp,每个子 sp 都是自己的结果,将被父使用。

How to assign an exec result to a sql variable?

declare @Result1 int = 0,
@Result2 int = 0,
@Total int = 0,
@projectID int,
@periodID int


exec @Result1 = [dbo].[QSP_getCount1] @projectID = 1,
@periodID = 12

exec @Result2= [dbo].[QSP_getCount2] @projectID = 1,
@periodID = 12

set @Total = @Result1 + @Result2

select @Total

存储过程 - 两者相同,只是使用差异 tables(returned 值为 1、15)

if OBJECT_ID('dbo.QSP_getCount1', 'P') is not null
drop procedure [dbo].[QSP_getCount1]
go

create procedure [dbo].[QSP_getCount1] @projectID int,
@periodID int
as
declare @NullTotal int = 0;

select @NullTotal = case when col1 is not null then @NullTotal + 1 else @NullTotal end,
@NullTotal = case when col2 is not null then @NullTotal + 1 else @NullTotal end,
@NullTotal = case when col3 is not null then @NullTotal + 1 else @NullTotal end,
@NullTotal = case when col4 is not null then @NullTotal + 1 else @NullTotal end,
@NullTotal = case when col5 is not null then @NullTotal + 1 else @NullTotal end
from tablename
where projectID = 1005 and periodID = 210

select @NullTotal

procs中没有RETURN statement,默认return值为0。使用RETURN @NullTotal代替select @NullTotal到return一个int 价值。 SELECT 在 proc return 的结果集中(在本例中包含 1 行,1 列),而不是标量。

代码中存在错误

declare @Result1 int = 0,
@Result1 int = 0,
@Total int = 0,
@projectID int,
@periodID int

@Result1 声明了两次