Converting a string to a datetime in SQL Server 2008 - sql-server

Simple question cannot seem to get right.
I have a table with a date in this format 20/09/2012 as varchar.
I need to convert to a datetime
Tried various solutions but cannot get it right.
Any suggestions?
Thanks

Using the CONVERT function with style 103 (British/European) seems to work for me:
DECLARE #input VARCHAR(20) = '20/09/2012'
SELECT
CONVERT(DATETIME, #input, 103)
With this approach, you could convert all your VARCHAR dates to their proper datatype - DATETIME - and store them as DATETIME in the first place ....
See Aaron Bertrand great blog post on bad habits to kick : mis-handling date / range queries for more background info on why it's really really bad to keep storing dates as VARCHAR columns ....

Related

Varchar(255) as MM/DD/YYYY HH:MM to Datetime format - SQL Server

I know there are a million of these date conversion questions, but I can't find the specific one to solve my problem.
I have a table with a column [Date] that contains data that is formatted as MM/DD/YYYY HH:MM, but is stored as a varchar.
[Date] (varchar(255),null)
12/22/2017 0:34
12/21/2017 21:33
12/21/2017 21:17
...
I need to run a query and filter by date range, so I need to figure out how to convert to a usable datetime format.
I've tried
WHERE CONVERT(VARCHAR(255), CAST([Date] AS DATETIME), 121) between #beg1 and #end1
But get the error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I've tried several other answers, but none were quite formatted the same as my data so the conversions didn't work.
Any help would be greatly appreciated
As many of us have mentioned, to real solution is fix the data type, which means altering the database.
First, to fix the data, you need to change the format to an ISO format, specifically here we're going to do with the ISO8601 format (yyyy-mm-ddThh:mi:ss.mmm). This will require a TRY_CONVERT and CONVERT (the first to change the data to a smalldatetime and the second to the formatted varchar):
UPDATE dbo.YourTable
SET YourDate = CONVERT(varchar(20),TRY_CONVERT(smalldatetime, YourDate, 101), 126);
Now we can alter the data type (to a smalldatetime as your data is accurate to a minute:
ALTER TABLE dbo.YourTable ALTER COLUMN YourDate smalldatetime NULL;
If you "must" leave it at a varchar (this is a bad idea, as your data has so many problems is so), then you need to use TRY_CONVERT in the WHERE, with the correct style code:
WHERE TRY_CONVERT(smalldatetime, YourDate, 101)
This is, however, a really bad idea as your data is severely flawed. For example, according to your data, the "date" '12/22/2017 0:34' is after today ('09/30/2020 21:25'), not before.
The code as you wrote it works fine. You probably have a badly formatted record or record where it is not in a date format. Try code like this to find those records. Any columns with a "NULL" value are ones where the try_cast could not succeed. These are the ones blowing up your query.
You can then choose to correct these values or simply exclude them from your query.
SELECT
[DateText], try_cast([DateText] AS Datetime) FROM Dates

SQL Server date separator dot not working while inserting data

When I insert a date like this '01.03.2020 21:35:12' it changes into '2020-01-03 21:35:12.000'.
I want to insert the date with DOT as the Date separator.
NOTE: I'm not using a stored procedure, just insert query.
This is an inferior choice in format, because nobody reading that code can be certain whether you meant January 3rd or March 1st. You can get there this way, but it is ugly, unintuitive, and equally non-self-documenting:
DECLARE #d varchar(30) = '01.03.2020 21:35:12';
SELECT CONVERT(datetime, #d, 104);
Much better to use a standard, unambiguous date format for literals. These are the only two formats not subject to misinterpretation by language, dateformat, or regional settings, and therefore don't need to be accompanied by cryptic style numbers:
DECLARE #d1 varchar(30) = '20200301 21:35:12',
#d2 varchar(30) = '2020-03-01T21:35:12';
SELECT CONVERT(datetime, #d1), CONVERT(datetime, #d2);
Background:
Recommended SQL Server Date Formats
Bad Habits to Kick : Mis-handling date / range queries
Dating Responsibly
I don't think you can change the display in SSMS from the YYYY-MM-DD TIME format. If you want to change the way you get the date back when selected, you can use the CONVERT or FORMAT functions.
CONVERT function: https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
FORMAT function: https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql
You may need to select your datetime twice with the CONVERT. Once for the date and once for the time in order to get the combination of formats you want.
-John

SSIS Convert m/dd/yyyy to yyyymmdd with inconsistencies

I'm loading many files into a SQL SERVER database. I have one flat file that has a Date Column coming in as string[DT_STR].
I have TWO "date fields" in my database. One is varchar, one is datetime.
Converting the datetime column is no issue, I just use Data Conversion/Derived Column if necessary. However, this varchar column is giving me trouble. Our database values for this column should be in yyyymmdd format. However, on this single file the format of the dates change.
Normally I'd do a SUBSTRING(...) expression here, but the difficulty is that the format of these dates change. some examples of values could be
08/16/2017
8/16/2017
08/6/2017
08/06/2017
10/6/2017
10/06/2017
This makes the challenge harder. I tried LEN([DATE]) == NUM_HERE ? do_THING : OTHER_CALC, but this approach failed because the length of 10/6/2017 is the same as 8/06/2017 which will give me the wrong result. Does anyone have a good workaround for this?
Perhaps a simple convert to date and then into the final format. If 2012+, use try_convert() to trap any bogus dates.
Example
Declare #YourTable Table ([SomeCol] varchar(50))
Insert Into #YourTable Values
('08/16/2017')
,('8/16/2017')
,('08/6/2017')
,('08/06/2017')
,('10/6/2017')
,('10/06/2017')
Select *
,Formatted = convert(varchar(8),convert(Date,SomeCol),112)
from #YourTable
Returns
SomeCol Formatted
08/16/2017 20170816
8/16/2017 20170816
08/6/2017 20170806
08/06/2017 20170806
10/6/2017 20171006
10/06/2017 20171006
Convert the varchar data to datetime and convert that to a formatted string
SELECT CONVERT(varchar,(CONVERT(datetime, '8/6/2017')),112)

How to make SQL Server to save datetime with AM/PM format?

I'm trying to make my SQL Server table datetime columns save datetime with AM/PM. How to make SQL Server to save datetime with AM/PM format?
Right now it saves date like this: 2012-01-23 14:47:00.000
Is it possible to save it 2012-01-23 02:47:00.000 PM ??
Or does SQL Server save the date and time in this format (2012-01-23 14:47:00.000) all the time and I need to convert it just on output and input?
Is it even possible to save it in this format (2012-01-23 02:47:00.000 PM)? Or does SQL Server save datetime in 24 hour format?
thanks indeed for any help. sorry for language. ;)
Internally the date and time are stored as a number.
Whether it's displayed in a 12 or 24 hour clock is up to the program formatting it for display.
As Andrew said, Datetime format is stored not as string. so, you can use CONVERT function to get the datetime value in approprate format. for example,
SELECT CONVERT(VARCHAR(20), GETDATE(), 100)
to learn more about datetime formatting, see this article
AM/PM serves only for visualization, if you need to display them, use CONVERT keyword:
SELECT CONVERT(varchar, YourDateTimeField, 109)
FROM YourTable
If you need to store AM/PM - it is makes no sense for datetime type, use varchar type instead.
You can simply use CONVERT function as following:
select CONVERT(VARCHAR,GETDATE(),108)
http://www.fmsinc.com/free/NewTips/SQL/AM_PM_time_format_in_SQL.asp
http://msdn.microsoft.com/en-us/library/Aa226054
http://blogs.msdn.com/b/kathykam/archive/2006/09/29/773041.aspx
Depending on the accuracy of the datetime you are storing you might be able to clean it up with
REPLACE(CONVERT (varchar, YourDateTimeField, 109), ':00.0000000', ' ')
This will not work if your date field is populated with GETDATE() as that means it will contain seconds and milliseconds but it will work if the field is populated by a user and seconds and milliseconds are all zeros

unable to convert varchar to date in sql server

in my data a column called 'duedate' which is in the varchar(5) format has dates stored in the following format '20110725' for 25th july 2011, is there a way in which i can convert this to date format
i tried using
cast(duedate as datetime)
which did not work
then i tried to convert it to bigint and then to datetime
cast( cast(duedate as bigint) as datetime)
which said
arithematic overflow error
Sorry for the confusion it was varchar(50) - typo error, and thanks a lot for the help ill try the things you guys mentioned
If the column is really varchar(5), then it can't have values like '20110725', because that would be 8 characters.
Maybe the values were truncated when they were inserted?
'20110725' shortened to 5 characters becomes '20117', and converting that won't work.
I guess the problem is something like that, because as Mladen Prajdic already said, converting '20110725' to datetime works perfectly.
Please see this table of valid date-time conversion codes. The code you will need is 112 which converts from yyyymmdd format.
CONVERT (datetime, duedate, 112)
how didn't it work? doing SELECT cast('20110725' as datetime) works perfectly for me.
Try running this on your table to find the values that aren't dates:
SELECT duedate
FROM your_table
WHERE ISDATE(duedate) = 0;
Like Christian said, a VarChar(5) won't be able to hold the value you're expecting it to either.

Resources