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

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.

Related

Select a datetime in Tsql, trim the milliseconds and return as a string

Problem: I want to select a date (stored as datetime) and return is as a string with the milliseconds trimmed off.
eg 2017-01-04 08:47:30.0000000 => "2017-01-04 08:47:30"
My current solutions:
I have got 3 statements which do the above:
Substring option
select
SUBSTRING(CONVERT(nvarchar,EventDate),0,20)
from EventsTable
Double convertions
select
CONVERT(nvarchar, CONVERT(datetime2(0),EventDate))
from EventsTable
Short nvarchar
select
CONVERT(nvarchar(19),EventDate)
from EventsTable
Allof the above solutions work and achieve my goal.
Question:
What is the best practice / most efficient way to achieve my goal?
Use a date style in your convert:
select CONVERT(varchar(19),EventDate,120)
from EventsTable
I would use this. It uses only one function, and sets the correct length for the varchar, and the format tells SQL Server the correct format you need.
Since style 120 is a standard you are sure that it the same no matter what localisation settings are on your DB or Session.
I ran all the three queries with the Execution Plan enabled with SQL Server 2008R2.
I received the cost equal in all of them ( 33% each).
All the three queries take the same time and resources.
However, the third one might help you with the less code being written.

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 to Datetime or Datetime 2

I need help because I can't convert it by myself. I got the following String:
20160803093000000
Inside the String there is the Date and Time: 2016-08-03 09:30:00:00
I need it as Datetime or Datetime2.
Here it is with the milliseconds (I entered another date, so you can see the change in the milliseconds):
DECLARE #t VARCHAR(50)
SET #t = '20160803093012345'
SELECT CONVERT(DATETIME,STUFF(STUFF(STUFF(STUFF(#t,9,0,' '),12,0,':'),15,0,':'),18,0,'.'))
I read something about loss of precision at the millisecond level, though. So there is still some need for research on the topic.
If you need the precision of the milliseconds, you can use DATETIME2 and just do:
SELECT CONVERT(DATETIME2,STUFF(STUFF(STUFF(STUFF(#t,9,0,' '),12,0,':'),15,0,':'),18,0,'.'))
I just read a great article regarding the precision. It says:
If you want to store the exact same value you had in DATETIME, just
choose DATETIME2(3), you get the same precision but it only takes 7
bytes to store the value instead of 8.
Here is the link for more information.
SELECT CONVERT(DATETIME2,STUFF(STUFF(STUFF(STUFF(#t,9,0,' '),12,0,':'),15,0,':'),18,0,'.'))
Works fine! Thank you a lot.

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

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)

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 )