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
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]
Select isnull(date_column_name,cast('1900-01-01' as DATE)) from table name
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]
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!