Change NULL values in Datetime format to empty string

前端 未结 10 1490
鱼传尺愫
鱼传尺愫 2021-01-07 16:50

I have a table which contains \'NULL\' values which are of type \'Datetime\'. Now i have to convert those into empty string but when when i use convert function



        
相关标签:
10条回答
  • 2021-01-07 17:28

    I had something similar, and here's (an edited) version of what I ended up using successfully:

    ISNULL(CONVERT(VARCHAR(50),[column name goes here],[date style goes here] ),'')

    Here's why this works: If you select a date which is NULL, it will show return NULL, though it is really stored as 01/01/1900. This is why an ISNULL on the date field, while you're working with any date data type will not treat this as a NULL, as it is technically not being stored as a NULL.

    However, once you convert it to a new datatype, it will convert it as a NULL, and at that point, you're ISNULL will work as you expect it to work.

    I hope this works out for you as well!

    ~Eli

    Update, nearly one year later:

    I had a similar situation, where I needed the output to be of the date data-type, and my aforementioned solution didn't work (it only works if you need it displayed as a date, not be of the date data type.

    If you need it to be of the date data-type, there is a way around it, and this is to nest a REPLACE within an ISNULL, the following worked for me:

    Select 
        ISNULL(
            REPLACE(
                [DATE COLUMN NAME],
                '1900-01-01',
                ''
            ),
        '') AS [MeaningfulAlias]
    
    0 讨论(0)
  • 2021-01-07 17:30
    Select isnull(date_column_name,cast('1900-01-01' as DATE)) from table name
    
    0 讨论(0)
  • 2021-01-07 17:33

    using an ISNULL is the best way I found of getting round the NULL in dates :

    ISNULL(CASE WHEN CONVERT(DATE, YOURDate) = '1900-01-01' THEN '' ELSE CONVERT(CHAR(10), YOURDate, 103) END, '') AS [YOUR Date]
    
    0 讨论(0)
  • 2021-01-07 17:41

    You could try the following

    select case when mydatetime IS NULL THEN '' else convert(varchar(20),@mydatetime,120) end as converted_date from sometable

    -- Testing it out could do --
    
    declare @mydatetime datetime
    set @mydatetime = GETDATE() -- comment out for null value
    --set @mydatetime = GETDATE()
    
    select 
    case when @mydatetime IS NULL THEN ''
    else convert(varchar(20),@mydatetime,120)
    end as converted_date
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题