Date time convert and retain blank - sql

I am trying to convert a column value to datetime.
CONVERT(datetime, ColName,105)
This converts all the blank values to default 1900-01-01 00:00:00.000.
I want to retain the blank values post conversion too.

If ColName only contains empty (var)char values, you can add NULLIF to the ColName like
CONVERT(datetime, NULLIF(ColName, ''),105)

If you're converting to a DATETIME then you won't be able to have a "blank" value, but you could have NULLs instead:
CASE WHEN ColName IS NULL OR LEN(LTRIM(ColName)) = 0 THEN NULL ELSE CONVERT(DATETIME, ColName, 105) END
This will convert any NULLs, blank strings, or whitespace to a NULL DATETIME, and convert everything else to a DATETIME with a value (assuming it's a valid date).

Blanks values will convert to SQL server default datetime value. Following query will help you not to convert the blank values. However it is better to have NULL instead of a ' '
SELECT CASE WHEN NULLIF(COLUMN,'') = NULL THEN
NULL
ELSE CONVERT(datetime, dd,105) END
FROM <TABLE>

First of all, storing dates as strings and using empty strings to represent missing values are very bad ideas. The problem can be fixed once and for all by converting that field into a nullable date or datetime.
Until that's done, or in order to do it easily, you can use the TRY_PARSE function available on all supported SQL Server versions. The earliest supported SQL Server version is 2012. 105 is the italian format, so :
SELECT TRY_PARSE(ColName as datetime USING 'it')
For example
select try_parse( '13-11-2018' as datetime USING 'it')
Will parse the string value into a datetime whose value is 2018-11-13 00:00:00.000. Anything that can't be parsed will return a NULL :
select try_parse( '' as datetime USING 'it')
Will return NULL.
In earlier versions one can use CASE WHEN or the equivalent IIF :
select IIF(TRIM(ColName)='',NULL,CONVERT(datetime, ColName,105))
Returning NULL is the only option because date types like date, datetime etc are scalar types just like int or decimal. There's no empty date or datetime. The only possibility is to have a NULL for a missing value or an actual date.
Trying to return some kind of blank value means that the dates will have to be converted back to strings.

Related

Convert String datetime to numeric date time

I have a column that I need converting from string date time to an actual data time data value.
The current format is as follows
15-JUN-22 10.24.10.414000
and I need to change it to the following format
15-06-22 10.24.10.414000
I use a stored procedure to automatically change the format, but it fails on this stage due to the non numeric characters.
Is there a way map or change all the string months to int values within the datetime? and if so how?
Converts used so far
TRY_CAST(CREATE_DATE AS DATETIME2(7)) AS CREATE_DATE
AND
CASE WHEN LEN([INTERVAL_START_DATE]) > 0 THEN TRY_CONVERT(DATETIME2, [INTERVAL_START_DATE], 103) ELSE NULL END
try this
CAST({your field name} as date) CONVERT(date,'{systemClock.UtcNow.ToString("o")}',127)

MM/dd/yyyy datetime data type resulted in an out-of-range value

I am inputting 2 date values in order to filter out from SQL query.
EXEC [Report].[usp_EmployeeReport_Detail] '01-01-2017','31-08-2019'
I am inputting the date as MM/dd/yyyy and the
WHERE clause contains
(j.StartDate BETWEEN #BegDate AND #EndDate)
I m getting the below error when executing the query.
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
I tried to convert the datetime result using the below way as well.
SELECT CONVERT(datetime,01-31-2017,101)
This returns 1894-05-25 00:00:00.000 as the response. How its possible?
As #Damien_The_Unbeliever has said,01-31-2017 using the Numerical expression, which evaluates to -2047.
-2047 means the day minus 2047 days from 1900-01-01, so result of date will be 1894-05-25 00:00:00.000.
So your query SELECT CONVERT(datetime,01-31-2017,101) same as SELECT CONVERT(datetime,-2047,101)
sqlfiddle
You can use the ANSI compliant format YYYYMMDD
SELECT CONVERT(datetime,'20170131',101);
instead of
DD-MM-YYYY 01-31-2017.
Or just add ' to contain the date '01-31-2017' like #fa06 answered.
Try this: u've missed the quote in date:
SELECT CONVERT(datetime,'01-31-2017',101)
try below way
SELECT CONVERT(CHAR,GETDATE(),1 )
it returns 08/13/18
in your case you missed the quote as a result output that type shown

Convert from varchar into date in SQL Server

This looks easy solution but I can't seem to figure out as to why this is not working for me. I have a column that has data like this:
DateField
----------
12/16/2016
11/06/2016
All I want to do is to convert from varchar into a date column, but I am getting this error:
Conversion failed when converting date and/or time from character string.
Here is my simple query:
select convert (date, DateField) as convertedField
from myTable
Nothing wrong with the two examples you have given. There are some bad dates in your table which cannot be converted to date.
Use TRY_CONVERT function for bad dates it will return NULL
select TRY_Convert(date,DateField)
From myTable
You should always store dates in DATE/DATETIME datatype.
If you want to see the records which cannot be converted to date then
select DateField
From myTable
Where TRY_Convert(date,DateField) IS NULL
If working with a specific date format like mm/dd/yyyy You can specify it in Convert() function like the following
CONVERT(DATETIME,DATAFIELD,101)
If it still is not working, use TRY_CONVERT() to get which rows are throwing this exception:
SELECT *
FROM TBL
WHERE TRY_CONVERT(DATETIME, DATAFIELD, 101) IS NULL
This will return rows that cannot be converted
TRY_CONVERT() will return NULL if conversion failed
Read more about DateTime formats here:
SQL Server CONVERT() Function tutorial
Read TRY_CONVERT MSDN Article
You need to specify the format of date time while formatting. The date in your table is currently in U.S format so you should pass the third argument 101 in your convert function.
SELECT CONVERT(date,[DateField],101) FROM myTable;
Working Fiddle here http://rextester.com/NYKR49788
More info about date time style here: https://msdn.microsoft.com/en-us/library/ms187928.aspx

Convert NVARCHAR to DATETIME and select distinct Year

SELECT DISTINCT YEAR(convert(varchar(max),OrderCreatedDate)) from webshop
The above sql query is producing this error:
Conversion failed when converting date and/or time from character string.
The value in the database is NVARCHAR and in the following format: DD/MM/YYYY 00:00:00 AM (/PM)
I would like to select the unique values for the year only!
thanks for any help
To avoid this sort of issues, date should be saved in DateTime type field Not in a string field.
Year() function parameter is a DateTime type not a String. So you should make sure that the string you are passing is convertible to a DateTime type. In this case you could trim out the time part with Left() function and use 103 style as below.
Fiddle demo:
--Example
declare #val nvarchar(50) = '28/10/2013 11:25:45 AM (/PM)'
select year(convert(date,left(#val,10),103)) myYear
--Applying to your query
SELECT DISTINCT Year(Convert(Date,Left(OrderCreatedDate,10),103)) FROM Webshop
UPDATE:
If you are getting errors, it could be due to your date format. i.e. Format of the string you have saved may not be as you have described (DD/MM/YYYY 00:00:00 AM (/PM)) in the question.
Please check with ISDATE() function before converting to date and identify which records are causing the problem and correct them.
Try this query to get all of them with invalid strings. Following query will return 0 for values with invalid formatting.
SELECT DISTINCT CASE WHEN IsDate(eft(OrderCreatedDate,10))=1 THEN
Year(Convert(Date,Left(OrderCreatedDate,10),103))
ELSE 0 END as myDate,
OrderCreatedDate
FROM Webshop
Or you could get only the records which are causing the problem as;
SELECT OrderCreatedDate
FROM Webshop
WHERE IsDate(Left(OrderCreatedDate,10)) = 0
select distinct year(CONVERT(NVARCHAR(255),CONVERT(SMALLDATETIME, columnName,105)))
Try this
SELECT DISTINCT YEAR(Convert(datetime,OrderCreatedDate,103)) from webshop
DD/MM/YYYY 00:00:00 AM (/PM) is the British format. See Convert

TSQL derived column with date convert that checks for non-date convertible strings

I have a date column with dates stored as strings, such as 20120817. Unfortunately, the text form field that populates this column is free text, so I cannot guarantee that an occasional "E" or "whatever" shows up in this column. And more than a few already have.
What I need to do is convert the string column into a date column. Of course the convert will reject the random string characters. Is there any way to create a derived column that will not only convert the strings but exclude the non-date convertible strings?
If there were no non-date convertible strings in the table, the following would work:
ADD [convertedDate] AS CONVERT(DATE, [stringDate], 102)
And it does work perfectly in a test table I created. But when I introduce other non-convertible strings, I receive the dreaded "Conversion failed when converting date and/or time from character string" error for obvious reasons.
Is there a function that will catch non-convertible elements that I can add on to this derived column code? Or is a view or function the only - or best - way to handle this? I played around with IsDate() with little luck.
Thank you!
There's a function called ISDATE(date), maybe you can use it in a CASE statement or in the WHERE part of the query... It depends on how you're doing it, maybe something like this
ADD [convertedDate] AS CASE WHEN ISDATE([stringDate]) = 1 THEN CONVERT(DATE,[stringDate], 102) ELSE NULL END
If you're using SQL Server 2012 you can make use of the try_convert function
http://msdn.microsoft.com/en-us/library/hh230993.aspx
It will work normally if the conversion succeeds but return null if the conversion fails
ADD [convertedDate] AS TRY_CONVERT(DATE, [stringDate], 102)
This should give you some ideas...
DECLARE #date1 varchar(50)
DECLARE #date2 varchar(50)
SET #date1 = '20120101'
SET #date2 = 'e20120101'
SELECT
ISDATE(#date1),
ISDATE(#date2),
CASE WHEN ISDATE(#date1) = 1 THEN CONVERT(SMALLDATETIME,#date1) END,
CASE WHEN ISDATE(#date2) = 1 THEN CONVERT(SMALLDATETIME,#date2) END