对基于日期的变量执行计算时未获得期望值

时间:2019-05-07 10:54:40

标签: sql-server

我试图在DaysRemainingInMonth语句中获取DaysInMonth / SELECT的十进制值,但是在执行时,我总是在列中获取0的值该声明。

这似乎很奇怪,因为它本质上是一个简单的除法练习:

declare @DaysinMonth int = DAY(EOMONTH(GETDATE())) -- 31
declare @DaysRemaining int = @DaysinMonth - DAY(GETDATE()) -- 24

SELECT 
      (DAY(EOMONTH(GETDATE())) - DAY(GETDATE())) as DaysRemaining
      ,@DaysinMonth as DaysinMonth 
      ,@DaysRemaining as DaysRemaining2
      , cast( (24/31) as decimal(18,10)) as Col1 -- Try casting and hard-coded values??
      , @DaysRemaining / @DaysinMonth as col2
      , 10 / 2 as WorkingExample

我至少应该得到0.774194...作为Col1的答案吗?我缺少明显的东西吗?

3 个答案:

答案 0 :(得分:1)

由于两个操作数都是整数,所以结果也是一个整数,其小数部分被切除。

将一个(或全部)操作数转换为decimal,因此结果也是decimal

...
, convert(decimal, 24) / 31 as Col1
, convert(decimal, @DaysRemaining) / @DaysinMonth as col2
...

答案 1 :(得分:1)

尝试将两个值都强制转换为数字

declare @DaysinMonth int = DAY(EOMONTH(GETDATE())) -- 31
declare @DaysRemaining int = @DaysinMonth - DAY(GETDATE()) -- 24

SELECT 
      (DAY(EOMONTH(GETDATE())) - DAY(GETDATE())) as DaysRemaining
      ,@DaysinMonth as DaysinMonth 
      ,@DaysRemaining as DaysRemaining2
      , cast( (24/31) as decimal(18,10)) as Col1 -- Try casting and hard-coded values??
      , cast(@DaysRemaining as numeric) / cast(@DaysinMonth as numeric) as col2
      , 10 / 2 as WorkingExample

答案 2 :(得分:1)

产生意外结果的原因是implicit data type conversion,当您将两个整数值相除时,结果也将是整数。

您可以尝试使用以下代码(再次由服务器进行隐式数据类型转换):

declare @DaysinMonth int = DAY(EOMONTH(GETDATE())) -- 31
declare @DaysRemaining int = @DaysinMonth - DAY(GETDATE()) -- 24

SELECT 
    (DAY(EOMONTH(GETDATE())) - DAY(GETDATE())) as DaysRemaining,
    @DaysinMonth as DaysinMonth,
    @DaysRemaining as DaysRemaining2, 
    (1.0 * 24 / 31) as Col1,
    1.0 * @DaysRemaining / @DaysinMonth as col2,
    10 / 2 as WorkingExample

或使用显式数据类型转换:

declare @DaysinMonth int = DAY(EOMONTH(GETDATE())) -- 31
declare @DaysRemaining int = @DaysinMonth - DAY(GETDATE()) -- 24

SELECT 
    (DAY(EOMONTH(GETDATE())) - DAY(GETDATE())) as DaysRemaining,
    @DaysinMonth as DaysinMonth,
    @DaysRemaining as DaysRemaining2, 
    CONVERT(decimal, 24) / 31  as Col1,
    CONVERT(decimal, @DaysRemaining) / @DaysinMonth as col2,
    10 / 2 as WorkingExample

输出:

DaysRemaining   DaysinMonth DaysRemaining2  Col1     col2           WorkingExample
24              31          24              0.774193 0.77419354838  5