1

在打印出一些涉及除以计算百分比的计算值时,我收到了除以零的错误。我不担心它正在发生,我只想知道如何打印 0 以及该行的其余部分,而不是打印错误,即 0%。

这是我的打印声明:

print cast(@usercode as varchar) + ' ' + @username + space(4) +
    'cr' + space(4) + cast(@totalUserVolumeCredit as varchar) + 
    space(4) + cast(@userUnpaids as varchar) + space(4) + 
    cast(@userDisputes as varchar) + space(4) + 
    cast((@userUnpaids + @userDisputes) as varchar) + space(4) + 
    cast(((@userUnpaids + @userDisputes)/@totalUserVolumeCredit) as varchar) + --error line
    space(4) + cast(@userRedirectsVolume as varchar);
4

3 回答 3

1
print cast(@usercode as varchar) + ' ' + @username + space(4) +
     'cr' + space(4) + cast(@totalUserVolumeCredit as varchar) + 
     space(4) + cast(@userUnpaids as varchar) + space(4) + 
     cast(@userDisputes as varchar) + space(4) + 
     cast((@userUnpaids + @userDisputes) as varchar) + space(4) + 
     case @totalUserVolumeCredit when 0 then '0' else
        cast(((@userUnpaids + @userDisputes)/@totalUserVolumeCredit) as varchar)
     end +
     space(4) + cast(@userRedirectsVolume as varchar);

演示

于 2013-01-23T15:02:20.830 回答
1

您的打印语句很复杂。我建议分解计算并分配变量,然后打印结果。您可以像这样使用T-SQL if/else

declare @calculation varchar(20)

if @totalUserVolumeCredit = 0
    set @calculation = '0%'
else
    set @calculation = cast((@userUnpaids + @userDisputes)/@totalUserVolumeCredit as varchar)

print cast(@usercode as varchar) + ' ' + @username + space(4) +
    'cr' + space(4) + cast(@totalUserVolumeCredit as varchar) + 
    space(4) + cast(@userUnpaids as varchar) + space(4) + 
    cast(@userDisputes as varchar) + space(4) + 
    cast((@userUnpaids + @userDisputes) as varchar) + space(4) + 
    @calculation  + -- former error line
    space(4) + cast(@userRedirectsVolume as varchar);

或者,从 SQL Server 2005 开始,您可以使用try/catch。简单的例子:

DECLARE @x int SET @x = 5
DECLARE @y int SET @y = 0

begin try
    PRINT @x / @y
end try
begin catch
    PRINT ERROR_MESSAGE()
end catch

使用 try/catch,您可以将麻烦的计算放入 try/catch 块中,并以适合您的问题域的任何方式处理它。

于 2013-01-23T15:00:30.137 回答
0

你可以改变这个表达式:

(@userUnpaids + @userDisputes) / @totalUserVolumeCredit

像这样:

isnull((@userUnpaids + @userDisputes) / nullif(@totalUserVolumeCredit, 0), 0)

当除数为 0 时,你总是会得到 0。

这是它的工作原理:

  1. nullif()当除数为 0 时,用 NULL 替换除数。

  2. 由于 NULL 除数,表达式的结果变为 NULL。

  3. isnull()将 NULL 结果变为 0。(您也可以改用更标准的coalesce()。)

于 2013-01-24T21:10:32.867 回答