SQL SERVER:在具有2个日期和1的列中使用datediff为空[关闭]

问题描述 投票:-2回答:1

SQL SERVER:

 REC_DATE = DATETIME (FORMAT: 'YYYY-MM-DD')  
 SHIPPED_DATE = NVARCHAR (FORMAT: 'MM/DD/YYYY')

首先,我想将出厂日期转换为相同的格式,但是还不能,当我使用转换为日期时间时,它保持相同的格式。

[其次,我想使用DateDiff来计算REC_DATE和SHIPPED_DATE,但是当SHIPPED_DATE为NULL时,我希望它返回NULL。

> REC_DATE      SHIPPED_DATE    RESULT
> 2020-05-05    05/07/2020        2 
> 2020-05-05    NULL             -13020 

我已经尝试了CASE,IIF,ISNULL,NULLIF,但仍然得到相同的结果。

sql-server tsql null datediff
1个回答
0
投票
/*
    FIRST PART: CONVERSION
         1. Convert your nvarchar to datetime (inner convert)
         2. Convert your result date into the desired format
         Note: The 3rd parameter in the convert (outer convert) defines the output format.
               In this case 120 for format yyyy-mm-dd. Try other formats like 101 to 114, and 121.
*/

DECLARE @NVarCharDateField  as varchar(10) = '05/25/2020'
SELECT  CONVERT(varchar(10), CONVERT(datetime, @NVarCharDateField),120) AS Result

/*
    SECOND PART: Treatment of NULLS
    It is not clear what you are trying to achieve
    The most common scenario would be to calculate days elapsed between reception and shipment.
    But you will have to make certain assumptions, and based on the scenario above NULL means Has not been shipped yet.
    So, NULL in the result will be OK. As long as you know the meaning based of the assumption.
    Ypu could also use a negative number (i.e. -1) to represent NOT SHIPPED
    Now lets calculate the elapsed days

*/

DECLARE @ReceivedDate   datetime    =   '05/01/2020'
DECLARE @ShippedDate    datetime    =   CONVERT(varchar(10), CONVERT(datetime, @NVarCharDateField),120)
SELECT 
        ReceivedDate    =   @ReceivedDate   
    ,   ShippedDate     =   @ShippedDate    
    ,   DaysElapsed     = DATEDIFF(DAY, @ReceivedDate, @ShippedDate)

SET @ShippedDate    =   NULL
SELECT  
        ReceivedDate    =   @ReceivedDate   
    ,   ShippedDate     =   @ShippedDate    
    ,   DaysElapsed     = ISNULL(DATEDIFF(DAY, @ReceivedDate, @ShippedDate), -1)

SELECT  
        ReceivedDate    =   @ReceivedDate   
    ,   ShippedDate     =   @ShippedDate    
    ,   DaysElapsed     = ISNULL(DATEDIFF(DAY, @ReceivedDate, @ShippedDate),  0)
© www.soinside.com 2019 - 2024. All rights reserved.