Conversion failed when converting date and/or time from character string Error - tsql

Select CONVERT(Date, '13-5-2012')
When i run the above T-SQL statement in Management Studio, i get i get the following error:
"Conversion failed when converting date and/or time from character string"
Is there away i can cast that value to a valid Date type successfully? I have such values in a nvarchar(255) column whose dataType i want to change to Date type in an SQL Server table but i have hit that error and i would like to first do a conversion in an Update statement on the table.

Specify what date format you are using:
Select CONVERT(Date, '13-5-2012', 105)
105 means Italian date format with century (dd-mm-yyyy).
Ref: http://msdn.microsoft.com/en-us/library/ms187928.aspx

In general, I'd suspect usually there is data which can't be converted in a column, and would use a case statement checking it's convertable first:
SELECT CASE WHEN ISDATE(mycolumn)=1 THEN CONVERT(Date, mycolumn, [style]) END
FROM mytable
I believe Convert relies on the SQL Server date format setting. Please check your dateformat setting with DBCC USEROPTIONS.
I suspect if you set the dateformat to dmy it'll understand:
SET DATEFORMAT dmy
GO
If even then it doesn't work, you can't find a style that matches your data, and if your data is in a consistant format, it's down to manual string manipulation to build it (don't do this if you can help it).

Try this....
Select CONVERT(Date,'5-13-2012')
Use 'mm-dd-yyyy' format.

CONVERT assumes that the original data can represent a date. One bad data item can throw the same conversion error mentioned here without pointing to the problem.
Using ISDATE helped me get around the bad data items.
SELECT CONVERT(DATE, CONVERT(CHAR(8), FieldName))
FROM DBName
WHERE ISDATE(FieldName) <> 0

You need to give the date format while conversion, this will resolve the error.
select convert(date, '13-5-2012' ,103)

Related

BigQuery Date Conversion From String

I've looked everywhere and can't find this answer. It's a pretty simple query, but I can't for the life of me figure out how to change the date.
I have a date coming in as a string, but it's not being picked up. The date is being brought in as 20170601 but I need it to be in a date format to be picked up in Tableau. I'm using Standard SQL and have tried to PARSE_DATE("%x", date) as parsed, cast(date as date), etc. and I keep getting Error: Failed to parse input string "20170918" or some variation of that error.
#standardSQL
SELECT
visitorid,
parse_DATE("%x", date) AS parse
FROM google.com:analytics-bigquery.LondonCycleHelmet.ga_sessions_20130910
The table is within `
Please advise!!
You could try doing a regex replacement to build the date string which you require:
SELECT
REGEXP_REPLACE('20170601', r"^([0-9]{4})([0-9]{2})([0-9]{2})", "\\1/\\2/\\3")
This would output 2017/06/01, which perhaps is the format you require. Actually, I don't know what format Tableau is expecting, but YYYYMMDD is usually the correct order for a date, because it will sort correctly as text. You may use any replacement you want, using the above query as an example.

Converting string timestamp into date

I have dates in a postgres database. The problem is they are stored in a string field and have values similar to: "1187222400000" (which would correspond to 07.08.2007).
I would like to convert them into readable dates usind some SQL to_date() expression or something similar but can't come up with the correct syntax to make it work.
There really isn't enough information here for a conclusion, so I propose this 'scientific-wild-ass-guess' to resolve your puzzle. :)
It appears this number is UNIX 'epoch time' in milliseconds. I'll show this example as if your string field had the arbitrary name, 'epoch_milli'. In postgresql you can convert it to a time stamp using this statement:
SELECT TIMESTAMP WITH TIME ZONE 'epoch' + epoch_milli * INTERVAL '1 millisecond';
or using this built-in postgresql function:
SELECT to_timestamp(epoch_milli / 1000)
either of which, for the example '1187222400000', produces the result
"2007-08-15 17:00:00-07"
You can do some of your own sleuthing with quite a few values selected similarly to this:
SELECT to_timestamp(epoch_milli/1000)::DATE
FROM (VALUES (1187222400000),(1194122400000)) AS val(epoch_milli);
"Well, bollocks, man. I just want the date." Point taken.
Simply cast the timestamp to a date to discard the excess bits:
SELECT to_timestamp(epoch_milli / 1000)::DATE
Of course its possible that this value is a conversion or is relative to some other value, hence the request for a second example data point.

convert string date(yyyy/mm/dd) to date format in db2

I am saving the date as varchar in db2 with yyyy/mm/dd format i need to convert it to date datetype in the query how to achieve this?
I tried
select DATE(CRDTR2) from ASAODLIB.SSLR204 where CRDTR2 BETWEEN
'2015/03/01' AND '2015/03/31';
query and got the below error
The syntax of the string representation of a datetime value is
incorrect.. SQLCODE=-180, SQLSTATE=22007, DRIVER=3.68.61
can someone help me.
If your DB2 version is new enough, use to_date: select DATE(TO_DATE(CRDTR2, 'YYYY/MM/DD')) from ...
...because it doesn't recognize that format. I'd turn it into *ISO first, via REPLACE:
SELECT DATE(REPLACE(CRDTR2, '/', '-'))
FROM ASAODLIB.SSLR204
WHERE CRDTR2 BETWEEN '2015/03/01' AND '2015/03/31'
Incidentally, there's a couple other things here.
You should be storing dates as an actual date type, which would make this a non-issue.
You shouldn't use BETWEEN, in preference for an exclusive upper-bound (< - the blog talks about SQL Server, but the problem is really due to representation. That, and most versions of DB2 allow you to specify fractional seconds in timestamps...).

T-SQL Conversion Failed when converting date/or time from character string

Perfmon isn't so kind with the way it creates the database when logging directly to SQL:
select top 1 Convert(datetime, CounterDateTime) from CounterData
returns
Conversion failed when converting date and/or time from character string.
The value of that cell is "2012-01-25 14:12:10.802". What is the proper way to convert this to a datetime field during selection?
CONVERT(DATETIME, SUBSTRING(CounterDateTime, 1, 23), 102)
I figured out that the following works (instead of the CHAR(24) it is):
select top 1 Cast(Cast(CounterDateTime as CHAR(23)) as datetime) from CounterData
Hoping there is a better solution though.
No better answer but this makes the taste a trifle less bitter.
CAST(CAST(CounterData.CounterDateTime AS CHAR(NN)) AS DATETIME) AS CounterDateTime
Also truncates the value so that additional T-SQL DateTime truncation to the minute, hour, etc is not needed.

Best method for varchar date validation in Sybase (T-SQL)?

I have a stored procedure which takes as its parameter a varchar which needs to be cast as a datetime for later use:
SET #the_date = CAST(#date_string AS DATETIME)
I'm expecting the date string to be supplied in the format "DD-MON-YYYY", but in an effort to code defensively, if for some reason it can't be cast successfully, I want to default to the system date and continue. In PL/SQL I could use exception handling to achieve this and I could do this fairly easily with regular expressions too, but the limited pattern matching supported out of the box by Sybase doesn't let me do this and I can't rely on third party libraries or extensions. Is there a simple way of doing this in T-SQL?
NB: using Sybase ASE 12.5.3, there is no ISDATE function
I'm having a similar issue. You might be able to do something like this:
SET arithabort arith_overflow off
SET #the_date = CAST(#date_string AS DATETIME)
IF #the_date is NULL
set #the_date = getdate()
SET arithabort arith_overflow on
However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch.
My goodness, if the question was about Microsoft SQL Server then we'd have been in business!
Sybase, sadly, is a whole 'nother database these days, since about 1997, in fact, give or take a year.
If the input format simply has to be 'DD-MON-YYYY' and no exceptions, then I think a fair amount of validation was be achieved by slicing the input using SUBSTR(), after first doing some simple things, such as checking length.
I thought that recent releases of Sybase (SQL Anywhere 11, for example) have regular expression support, however, although it's been a while since I've had to suffer T-SQL. Some googling leaves me in rather more doubt.
Can't you do something like this:
SELECT #the_date = CASE #date_string
WHEN '[0-9][0-9]-[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]'
THEN CONVERT(datetime, #date_string)
ELSE GETDATE()
END
?
Found this in the second result in Google when searching for "validate date string sql".
----Invalid date
SELECT ISDATE('30/2/2007')
RETURNS : 0 (Zero)
----Valid date
SELECT ISDATE('12/12/20007')
RETURNS : 1 (ONE)
----Invalid DataType
SELECT ISDATE('SQL')
RETURNS : 0 (Zero)
Make sure SQL Server knows the order of Days, Months and Years in your string by executing
SET DATEFORMAT mdy;
Did you try convert instead of cast?
select convert( datetime , #date_string )