Blank values in Date column returning as 1900/01/01 on running SELECT statement
Asked Answered
M

3

12

The column [PAYOFF DATE] has some blank values and some values in mm/dd/yy format.

I have to replace '/' with '-' and return the date as yyyy-mm-dd. The below query is doing it. The problem is that for all blank values, I am getting results as 1900-01-01.

Is it possible to replace 1900-01-01 with null and return other valid date values as is in yyyy-mm-dd format?

I am using SQL Server.

SELECT
cast(replace(a.[PAYOFF DATE],'/','-') as date) 
FROM MTG a
Malinowski answered 9/4, 2014 at 20:20 Comment(2)
This may put you on the right track. You can convert the Datetime to a string since datetime cannot return an empty value. #15554869Chandigarh
@Chandigarh - I looked up that link already but in my case, I have to do two things, first replace '/' with '-' and then return NULL when date is in 1900-01-01 hence I am facing problem performing these two operations together in one statement.Malinowski
C
23

You dont need to do the string manipulation as you have shown in your question. If you have dates stored in mm/dd/yyyy format just cast it as DATE.

SELECT cast(a.[PAYOFF DATE] AS DATE) 
FROM MTG a 

For 1900-01-01 values, since you are converting from a string data type to Date, String datatype can have Empty strings but Date datatype cannot have empty date values, It can have either a date value or NULL value.

Therefore you need to convert the empty string to nulls before you convert it to date. 1900-01-01 is just a default value sql server puts in for you because Date datatype cannot have an empty value.

You can avoid having this sql server default value by doing something like this.

SELECT cast(NULLIF(a.[PAYOFF DATE],'') AS DATE) 
FROM MTG a 
Coerce answered 9/4, 2014 at 20:35 Comment(0)
S
3

CASE WHEN [Pay Date] = '' THEN NULL ELSE TRY_CONVERT(DATE, [Pay Date]) END

Sitnik answered 3/1, 2020 at 21:26 Comment(0)
C
0
[dateField] [datetime] NULL

Be careful if you want to stuff your nullable DateTime field like above with certain value such as Today's date, because t-SQL datetime field would supply a default 1900/01/01 when a datetime field is empty not null:

First, test for empty, NULLIF(dateField, '').

Second, replace the null with your desired value.

To conclude, to stuff empty-or-null datefield, do

select isNull(NullIF(dateField, ''), getDate()) as myNonEmptyDate

   
Chianti answered 26/4 at 0:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.