SQL Server十进制变量分配?

标签 sql tsql types casting sql-server-2012

我正在尝试编写一个存储过程,但是我得到了意外的除以0的异常。

我将其范围缩小到以下示例。

为什么在世界上这样做:

    declare @A decimal;
    declare @B decimal;
    declare @C decimal;

    set @A = 4;
    set @B = 9;
    set @C = @A/@B 

    select @A/@B as 'Expected'
    select @C as 'Wut'

结果呢?
    Expected
    ---------------------------------------
    0.4444444444444444444

    (1 row(s) affected)

    Wut
    ---------------------------------------
    0

    (1 row(s) affected)

最佳答案

问题是您尚未为decimal类型指定比例。从MSDN:

s (scale)

The number of decimal digits that will be stored to the right of the decimal point. This number is substracted from p to determine the maximum number of digits to the left of the decimal point. Scale must be a value from 0 through p. Scale can be specified only if precision is specified. The default scale is 0; therefore, 0 <= s <= p.



因此,当您尝试将@A/@B存储回@C时,小数部分会被截断。

注意:
declare @A decimal(18, 3);
declare @B decimal(18, 3);
declare @C decimal(18, 3);

set @A = 4;
set @B = 9;
set @C = @A/@B 

select @A/@B -- 0.44444444444444444444
select @C    -- 0.444

关于SQL Server十进制变量分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23016501/

相关文章:

php - Mysql 使用 AND 和 OR 进行搜索

sql-server - 您可以对数据透视表中的行和/或列进行小计吗?

sql-server - T-SQL如何向用户授予角色

typescript - 如何从 typescript 中的数组中提取类型?

types - 将数字基元(i32、f64 等)转换为字节表示

sql - 在 SQL Server GRANT 中转义反斜杠

mysql - SQL。如何管理运算符 GROUP BY

sql - 如何列出 SQL 查询中使用的所有列(包括架构和表)

sql - TSQL - 在Where 子句中使用派生的选择列

python - 联合类型实际上存在于 python 中吗?