CASTing a datetime to string if null value - keeping original datetime formatting

故事扮演 提交于 2020-01-17 07:03:31

问题


I have the following part of my query:

ISNULL(cast(fd.decision_date as varchar(20)), 'PENDING') as facility,
ISNULL(cast(cd.decision_date as varchar(20)), 'PENDING') as corporate,
ISNULL(cast(cb.creation_date as varchar(20)), 'PENDING') as billing

My values are originally of datetime datatype, but what I want to do is return the word 'PENDING' if the value is NULL.

With the code above, my results are casted to a varchar, thus returning something like:

Aug 20 2013 9:35AM 

instead of 2013-08-20 09:35:54

Suggestions would be greatly appreciated.


回答1:


Replace cast with convert and appropriate style: Convert syntax & styles, eg:

ISNULL(convert(varchar(20), fd.decision_date, 120), 'PENDING') as facility,



回答2:


Instead of cast(... as varchar(20)), use convert with a style number, this is exactly what that's for.

SELECT CONVERT(CHAR(19), GETDATE(), 120);

So your query becomes:

COALESCE(CONVERT(CHAR(19), fd.decision_date, 120), 'PENDING') as facility,
COALESCE(CONVERT(CHAR(19), cd.decision_date, 120), 'PENDING') as corporate,
COALESCE(CONVERT(CHAR(19), cb.creation_date, 120), 'PENDING') as billing


来源:https://stackoverflow.com/questions/18387612/casting-a-datetime-to-string-if-null-value-keeping-original-datetime-formattin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!