I'm using SQL Server 2008 R2. I've been given data that includes numerous varchar fields in the format mm/dd/yyyy hh:mm:ss.mmmmmm AM. Here are some examples:
1/16/2013 10:31:38.000000 AM
11/12/2013 3:42:12.000000 PM
12/6/2013 2:42:46.000000 PM
I'd like to convert into a datetime format so I can work with them, but am having problems... I've found various sites that list the different date time formats (such as this one), but this format isn't listed anywhere.
I've tried casting and converting in various different ways, including:
select CAST (field as datetime) from table;
select CONVERT (datetime, field, 101)
from table;
But I keep getting this error:
"Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string."
I presume because the format my field is in isn't standard so SQL can't recognize it?
Any help would be appreciated. Apologies if this has been covered before - I've spent 4 hours searching this and other sites but can't find the answer...
Shouldn't you be casting to Datetime2 type instead? The Datetime has precision only as high as to milliseconds.
Related
I've linked Google data studio with a MySQL database using the standard connector. Almost everything works fine except for date and datetime fields.
I have these 2 fields in phpmyadmin (field name, field type, output):
Validated_date datetime 2017-09-27 12:31:04
Expiration_date date 2017-12-24
In Data Studio I've set these types, but none of them are recognised:
Validated_date Date Hour (YYYYMMDDHH)
Expiration_date Date (YYYYMMDD)
I tried to format the field with date_format in my SELECT:
DATE_FORMAT(p.Expiration_date, '%Y%m%d') AS "Expiration Date"
I even tried other date_formats but they're never recognised as dates in Data Studio:
DATE_FORMAT(p.Expiration_date, '%Y/%m/%d') AS "Expiration Date"
DATE_FORMAT(p.Expiration_date, '%Y-%m-%d') AS "Expiration Date"
Any idea?
I had the same issue. My approach to solve this is to modify the date format within Google Data Studio by creating a new dimension, reformatting the mySQL Datetime into the desired format.
In your example you use DATE_FORMAT. I wonder if you apply this in Data Studio (which does not know DATE_FORMAT) or in mySQL?. If you do it in data studio and leave your mySQL/phpmyadmin untouched you can use this:
TODATE(your-date-field, 'DEFAULT_DASH', '%Y%m%d')
This will take the date format YYYY-MM-DD with optional time in HH:ii:ss and reformat it into YYYYMMDD which works with data studio.
I've never tried directly with Data Studio but when I extract datetime fields from mySQL to use in BigQuery I use:
CONVERT(DATETIME2(0), [DATETIME_FIELD])
This removed any milliseconds which generally cause problems and convert it to a recognisable datetime format for Google
I have used the follow formule and working for me:
TODATE(yor-field-from-mysql, '%Y-%m-%dT%H:%M:%S', "%Y%m%d%H%M")Then I choose ***YYYYMMDDhhmm*** format in DataStudio. I hope it helps.
Edit: In this case, date came from javascript using moment.js
I had the same issue. For me, the only solution was create a formula this way:
CONCAT(SUBSTR(field, 1, 4), SUBSTR(field, 6, 2), SUBSTR(field, 9, 2))
and use this as AAAAMMDD format
I need help. I keep getting a "Conversion failed when converting date and/or time from character string" error right before the INSERT statement. I can see that the problem stems from either the [nowtime] or the [a_Timestamp] because of the datatypes, and I have to convert them to the same type. However somehow I can't get it to work no matter what I try. In the background [a_Timestamp] is CHAR(13) and #nowtime is CONVERT(time,CONVERT(char(8), GETDATE(), 108)).
The purpose of the full query is to monitor a DBs past 1, 5 and 10 seconds of data, so the time operations are vital and must be quick. If you need more of the code (or all of it) im happy to provide!
CREATE TABLE #base
(
[date] CHAR(8),
[a_MemberId] CHAR(5),
[a_Timestamp]CHAR(8),
[nowTime] TIME
)
INSERT INTO #base
([date],
[a_MemberId],
[a_Timestamp],
[nowTime])
SELECT [date] AS [date],
[a_MemberId] AS [a_MemberId],
SUBSTRING([a_Timestamp],0,7) AS [timeStamp],
#nowTime AS [nowTime]
FROM [ObserverDB].[dbo].[onti_ord] WITH (NOLOCK)
WHERE [date] = #TodaysDateTEST AND [a_Timestamp] < #nowTime
ORDER BY [date]
This is probably culture related. Your string is converted implicitly and your culture does not fit to the stored format. It is always a bad idea to store date and/or time values as text.
There is only one sure format: ISO8601 which means (one of many examples)
yyyy-mm-ddThh:mm:ss.ttt (e.g. 2016-08-17T13:11:23)
In this line you are comparing your values. Obviously one of them is treated as string and one as date-time value
WHERE [date] = #TodaysDateTEST AND [a_Timestamp] < #nowTime
You must make sure (by using CONVERT (details here) with the proper format number), that a date and/or time value is converted to string exactly to the same format as your strings stored (sargable, therefore faster), or to convert your stored values to real date and/or time values and compare them type safe (much cleaner).
Of course the advise should be: Change the database to store this propperly, but - as you stated in comment - you have to deal with this...
Good luck :-)
A silly question maybe but I wanted clarification. I've created a script that has a date parameter like so:
DECLARE #dateparam as datetime
SET #dateparam = '01-01-2013 00:00:00'
This looks like it is working when I test it even if the date string is not in "correct" format yyyy-MM-dd hh:mm:ss. I changed my computer regional settings to English and the script still did what it was supposed to do.
Is this because of SQL Server 2008 R2 that I have in my computer that it knows how to convert the date or can I ran into trouble with using a dateformat like I have used?
Converting 01-01-2013 won't expose issues such as which 01 is the month, and which is the day.
It's not a safe format.
The safe formats (for converting to datetime, rather than to datetime2) are:
YYYYMMDD 20121201
YYYY-MM-DD'T'hh:mm:ss 2012-12-01T10:43:29
YYYY-MM-DD'T'hh:mm:ss.mil 2012-12-01T10:43:29.337
Stick to those and only those. (The examples all represent the 1st December 2012)
Or, better yet, don't treat dates as strings at all, if you can avoid it. If you're, for example, calling SQL Server from .NET code, keep that dates as DateTimes in your code, and let ADO.NET and SQL Server deal with any required translations to make them become datetimes - without translating them to and from strings.
You're making an implicit conversion from something that looks like a date, but inf fact is a string ( '01-01-2013 00:00:00'). Rather than trusting on SQL Server to make the correct guess in what format the string is in, you should make the conversion explicit by specifying the format.
This can be done by using CONVERT (not CAST) and specify a 'style'. The different styles are listed here: http://msdn.microsoft.com/en-us/library/ms187928.aspx.
I have an Excel file that contains a column full of dates in the dd/mm/yyyy format. When I try to import it using openrowset, it said that there was a datatype mismatch. I have a table where the date is defined as type date. Now, I know that the default date format in SQL Server is yyyy-mm-dd. How can I avoid this conflict? Is there a way I can make the default date type be dd/mm/yyyy? I need to do this import operation everyday and it has to be automated and so I cannot afford it to fail in between. I tried using sp_addlanguage to make it British as the default date type is dd/mm/yyyy there, but it didn't work :(. I'm using SQL Server 2008 and Windows 7, if that is of any help. Please help me out! Thanks!
You could CONVERT the incoming data before you insert it. So, in the openrowset statement, where you select the field, you could surround it with a CONVERT statement. Here's an example:
print convert(date,'19/07/2010',103)
This is a UK style date, but if you run it you can see that it's converted it to SQL-friendly format.
I have a table where unfortunately a number of dates are stored as strings.
I have a number of reports that cast them to datetimes and filter by them. This was working fine until today when all of a sudden i'm getting this error
"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
The dates are all stored in the format of "yyyy-mm-dd" and are all valid.
If I run the following SQL statement
SELECT CAST('2010-06-02' AS DateTime)
I would expect to get "2010-06-02" however as of today I'm getting "2010-02-06" something has changed with the way SQL formats dates. I've had a look in regional settings on the server and it all looks to be correct.
What else could be causing this?
Try setting the format explicitly
select convert(datetime, '2010-06-02',101)
An unambiguous way of getting this conversion is to do the following:
SELECT CAST(replace('2010-06-02', '-', '') AS DateTime)
And that will always be interpreted as YYYYMMDD, ignoring the set dateformat ydm declaration or any cultural settings that the database has.
Q1: What else could be causing this?
The local, You probably are under the local101(US) and put data from 103 (British/French)
Like barry sad use convert