在存储过程中添加两个数值将导致空值

时间:2019-02-12 18:13:08

标签: sql sql-server tsql

在存储过程中,我试图将两个数字值相加

DECLARE @tradeamt1 NUMERIC(23,2)

DECLARE @tradeamt3 NUMERIC(23,2)

DECLARE @value NUMERIC(23,2)

if (@retVal1 = 0)
BEGIN
    SELECT  @row_count = count(1), 
    @tradeamt1=Sum(trade_amt) ,
    @units= Sum(curr_shrs_num) 
FROM [csr_staging].[dbo].[fi_impact_source] WITH(NOLOCK) 
Where acct_id = 'BANKFEES'
and SD_ID >= EFF_DT 
print @tradeamt1
END

if(@retVal3 > 0)
BEGIN


select @row_count = count(1) - @retVal3 + @row_count,@tradeamt3=Sum(trade_amt),@units= @units +Sum(curr_shrs_num) - @currshares
FROM [CSR_Staging].[dbo].[fi_impact_source]  WITH(NOLOCK) 
where (clearing_code = 'MBS'or clearing_code = 'CNS') and (SD_ID >= EFF_DT)

print @tradeamt3

END

set @value = @tradeamt1 +@tradeamt3

此值为null,而不是添加tradeamount1 = 1.00和tradeamount3 = 191432650.13

2 个答案:

答案 0 :(得分:0)

这很可能是因为未初始化tradeamt1和tradeamt3,并且由于某种原因也未分配值。

您可以使用

对其进行初始化。
DECLARE @tradeamt1 NUMERIC(23,2) = 0

DECLARE @tradeamt3 NUMERIC(23,2) = 0

DECLARE @value NUMERIC(23,2) = 0

让我知道是否有帮助。

:)

答案 1 :(得分:0)

也许这可能适合您的SP:

declare   @tradeamt1 numeric(23, 2) = 0
        , @tradeamt3 numeric(23, 2) = 0
        , @value numeric(23, 2) = 0

select @row_count = 0, @units = 0

if @retVal1 = 0
    select @row_count = count(1)
        ,  @tradeamt1 = isnull(sum(trade_amt), 0)
        ,  @units     = isnull(sum(curr_shrs_num), 0)
    from [CSR_Staging].[dbo].[fi_impact_source] with (nolock)
    where acct_id = 'BANKFEES'
        and SD_ID >= EFF_DT

if @retVal3 > 0
    select @row_count = @row_count + count(1) - @retVal3
        ,  @tradeamt3 = isnull(sum(trade_amt), 0)
        ,  @units     = @units + isnull(sum(curr_shrs_num), 0) - @currshares
    from [CSR_Staging].[dbo].[fi_impact_source] with (nolock)
    where clearing_code in ('MBS', 'CNS')
        and SD_ID >= EFF_DT

set @value = @tradeamt1 + @tradeamt3

使用isNull(可确保@tradeamt1@tradeamt3都不为空