如何使用datediff将datetime2列转换为bigint

时间:2019-06-12 13:54:44

标签: sql-server date-conversion bigint datetime2

我有一个名为'order_confirmation_date'的列,它是Datetime2格式,我需要它与bigint一起使用下面的查询,该查询使用datediff黑白列值和getdate()。

SELECT 
   datediff(day, convert(VARCHAR(10), 
   NULLIF((                                             
       CASE WHEN cast(replace(convert(varchar(10),cast(fpo.order_confirmation_date as date)),'-','') as bigint) >= cast([dbo].[fnGetFormatedDate](getdate(), 'YYYYMMDD') AS BIGINT)

            THEN fpo.order_confirmation_date                                                
            ELSE NULL

            END
                                        ), 0),112), GETDATE()) * (- 1) AS ordconf_x_days_fromtoday
    FROM bidb.fact_purchase_order fpo
  

消息50000,级别16,状态2,行1409操作数类型冲突:datetime2   与bigint不兼容

1 个答案:

答案 0 :(得分:0)

您已经有约会。别这么努力地工作,让您的约会成为约会。

declare @t table (order_confirmation_date datetime2);
insert @t 
values ('20190524'),('20190722'),(CAST(GETDATE() AS date))

SELECT 
  fpo.order_confirmation_date,
  datediff(day, CAST(getdate() AS date),fpo.order_confirmation_date)
 AS ordconf_x_days_fromtoday
FROM @t fpo

结果:

+-----------------------------+--------------------------+
|   order_confirmation_date   | ordconf_x_days_fromtoday |
+-----------------------------+--------------------------+
| 2019-05-24 00:00:00.0000000 |                      -19 |
| 2019-07-22 00:00:00.0000000 |                       40 |
| 2019-06-12 00:00:00.0000000 |                        0 |
+-----------------------------+--------------------------+

编辑:如果您希望过去的日期返回NULL

SELECT 
  fpo.order_confirmation_date,
  CASE 
    WHEN fpo.order_confirmation_date < GETDATE() THEN NULL
    ELSE datediff(day, CAST(getdate() AS date),fpo.order_confirmation_date)
  END AS ordconf_x_days_fromtoday
FROM @t fpo