expiredDate nvarchar() column contains data like 22-12-2022 00:00:00 and null.
SELECT ISNULL(CONVERT(Date, expiredDate), '')
FROM tablename
Result for null is default date 1900-01-01 - I want it to be blank or empty.
As the column is getting converted to datetime null is converted to the default date.
Required date should be in yyyy-MM-dd format and null as empty
You may use CONVERT here on the raw date to generate a string, and then COALESCE missing null values into empty string:
SELECT expiredDate,
COALESCE(CONVERT(varchar(10), expiredDate, 120), '') AS expiredDateText
FROM yourTable;
You can try below query.
select case when ISDATE(expiredDate) = 0 then '' else convert(varchar,convert(date,expiredDate)) end as YourColumnName
The ISDATE() function checks whether the input data is a valid date or not. This includes NULL too. It will return Zero (0) if the data is not a date.
If you culture is en-us then by default you will get the date in YYYY-MM-DD format.
You can also use Format function in SQL Server to get the date in your expected format.
More information about format function can be found at below link.
https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql?view=sql-server-ver15
You've have stumbled upon one of the odd(annoying) quirks in SQL Server where blank string becomes 1900-01-01 when cast to DATE. Your CONVERT() sets the column type to DATE, and then when you do ISNULL, it implicitly casts empty string to DATE. Why it returns 1900-01-01 instead of an error, I have no idea
Example of Empty String to Date Odd Behavior
SELECT CAST('' AS DATE)
--Returns 1900-01-01
Parse Date to Correct DATE data type and Then Format
How I'd recommend this is first converting your NVARCHAR column to the correct DATE data type. Using TRY_CAST allows any invalid dates to not cause the whole query to fail, instead will return NULL. FORMAT() then allows you to format the DATE anyway you like, and ISNULL will change NULL to empty string
DECLARE #YourTable TABLE (ID INT IDENTITY(1,1),expiredDate nvarchar(20))
INSERT INTO #YourTable
VALUES ('22-12-2022 00:00:00'),('31-12-2022 00:00:00'),('02-02-2022 00:00:00'),(NULL)
,('40-02-2022 00:00:00') /*Bad date for testing purposes*/
SELECT *,FormattedExpiredDate = ISNULL(FORMAT(B.ExpiredDateWithCorrectDateType,'yyyy-MM-dd'),'')
FROM #YourTable AS A
/*Format to YYYY-MM-DD (culture agnostic date format) and then use TRY_CAST(). If date is invalid, will return NULL*/
CROSS APPLY (SELECT ExpiredDateWithCorrectDateType = TRY_CAST(SUBSTRING(expiredDate,7,4) + SUBSTRING(expiredDate,4,2) + SUBSTRING(expiredDate,1,2) AS DATE)) AS B
Results:
ID
expiredDate
ExpiredDateWithCorrectDateType
FormattedExpiredDate
1
22-12-2022 00:00:00
2022-12-22
2022-12-22
2
31-12-2022 00:00:00
2022-12-31
2022-12-31
3
02-02-2022 00:00:00
2022-02-02
2022-02-02
4
NULL
NULL
5
40-02-2022 00:00:00
NULL
Related
An import has rendered a date [YEAR] as varchar and I need to convert it to a proper date.
The conversion fails I believe, because SQL cannot recognise d/mm/yyyy equal to dd/mm/yyyy.
How do I get SQL to convert / cast this into a date or timestamp?
SELECT [YEAR], LEN([YEAR]) AS ColumnLength
FROM [IDW_Dev]
YEAR ColumnLength
10/07/2020 10
8/07/2020 9
14/08/2020 10
I tried this, and this should normally work:
, CAST([YEAR] AS DATE) AS AUDIT_DATE
Conversion failed when converting date and/or time from character string.
Here's a demo using the convert function, just because I felt like testing if it worked with all variations of DD and MM in the string.
Convert has most layouts built in, 103 is for British/French format with slashes.
SELECT SampleDate
, CONVERT(Datetime2, SampleDate, 103) AS ConvertedDate
FROM (
VALUES ('1/2/2020')
, ('1/02/2020')
, ('01/2/2020')
, ('01/02/2020')
)Samples(SampleDate)
I tired this
select CONVERT(DATE, '31/12/18', 103) as rDatum
but I get error:
Conversion failed when converting date and/or time from character string.
What is the right way to convert string which is date with short year to DATE in TSQL?
You were very close...
This is british/french format with a 2-digit year.The format code is 3 (103 is with a 4-digit year)
Try this
select CONVERT(DATE, '31/12/18', 3) as rDatum
Try this
SET DATEFORMAT DMY
INSERT INTO targetTable (rDatum, col2 etc)
SELECT CAST(someDate AS DATE) , col2 etc
FROM sourceTable
I used following query to insert the data :
CASE(isdate([Date]))
WHEN 1 THEN [date]
WHEN 0 THEN cast(substring([Date],0,5) - 2 as smalldatetime)
ELSE [date] END
Now, datetime column has date in smalldatetime format. How to convert smalldatetime formatted date to datetime format whereas column type is datetime.
Example: For Numeric date 41298 it resulted into 1911-04-21 00:00:00 but actual expected result was 2013-01-26 00:00:00.000
I think you are looking for something like this:
(CASE WHEN ISNUMERIC([Date]) = 1
THEN DATEADD(day, CAST([Date] as int), '1899-12-31')
WHEN iSDATE([Date]) = 1
THEN CAST([date] as smalldatetime)
END)
The value 41298 looks like an Excel formatted date. These start counting from the last day of 1899.
I have tried your given value and it convert to expected result please have a look;
SELECT CAST(CAST(41298 AS smalldatetime) AS DATE) AS Date
SELECT CAST(41298 AS smalldatetime) AS Date
Output:
Another option is DateAdd
Select DateAdd(DAY,41298,'1900-01-01')
Returns
2013-01-26 00:00:00.000
When I use the below statement to set the TD_BOOK_COMPLETED_ON to blank , it gives me January, 01 1900 00:00:00 , how can I set my Date field to ''?
Code:
case when BOOK_COMPLETED='Y' then TD_BOOK_COMPLETED_ON else '' end as END_DATE
An empty string literal is shorthand for the default datetime value, which is 1900-01-01 00:00:00. Only valid datetime values in the documented range, or NULL, can be stored in a datetime column.
Instead of an empty string, you probably want to use NULL to indicate unknown or not applicable.
A date is not a string. Set it to NULL instead. It's interpreting an empty space '' as a 0, which is 1/1/1900.
You need to CAST or CONVERT the date to VARCHAR
CASE when BOOK_COMPLETED='Y' then CAST(TD_BOOK_COMPLETED_ON AS VARCHAR(24)) else '' end as END_DATE
or set the date to NULL
i have a column (nvarchar),there are datetimes in there but as a string.I want to change that column's type into smalldatetime but before i want to format all string dates into a same datetime format.But i cant succeed it.Some of them are like this "2007-07-10",some of them are reverse of this "02.07.2008". How can i change them into one format for example dd.mm.yyyy.
(ms sql server 2008)
If you only have those 2 formats, this is how you can do it.
I am assuming
'02.07.2008' has format 'dd.mm.yyyy'
'2007-07-10' has format 'yyyy-mm-dd'
If you have more formats than that, you have to alter the 'case' in the 'select' clause accordingly
declare #t table (a varchar(12))
insert #t values ('02.07.2008')
insert #t values ('2007-07-10')
select convert(date, a, case when charindex('-',a) = 5 then 21 else 103 end)
from #t
Output
2008-07-02
2007-07-10
The format is standard for a date field, but if you want to store it as a varchar, you can format it as dd.mm.yyyy like this instead.
select replace(convert(varchar, convert(date, a, case when charindex('-',a) = 5
then 21 else 103 end), 103), '/', '.')
from #t
Output
02.07.2008
10.07.2007
I have to point out that you should always store a date as a date and not a varchar in the database when possible.
You can't do it unless you know the exact format.
Think about the different formats - in some countries the month comes first, while in the other it's the day. So if you don't know whether 02.07.2008 means July 2th, or it means Feb 7th, then you can't possibly accomplish your task.