How to convert an int column ,Birthdate( sample value 20090301) to a date column in the format(01/03/2009)
Sql Server 2000
I was trying to convert some thing like below
select * from tabl
where
cast(dob as datetime)>='01/03/2009'
which gives an error
Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type datetime.
SQL Server doesn't allow you to cast int -> datetime directly, but if you're sure you can cast it to nvarchar first and then cast it to date.
For your question here's an example
declare #test int = 20090301
select CONVERT(datetime, CAST(#test as nvarchar), 112)
112 is the format you mentioned, here's the list of all possible formats for Convert function.
try this !
select * from tabl
where
cast(convert(char(8),dob, 112) as date)>='2009-03-01'
Related
I have gone through a bunch of posts here with this error and tried changing data types and used Convert but nothing seems to fix this. So I would like to ask for some help here. I will try to give as much info, but feel free to ask if its not enough.
This is where I am getting the error:
Insert into prompt(ID, Date)
select
ROW_NUMBER() over (order by b.IDLoc),
[dbo].[fn_GetGPtime](cast (replace(DateCollected, '/', '-') + ' ' + a.UTCTime as datetime))
from
Img a
inner join
Tloc b on a.Filename = b.filename
order by
b.IDLoc
The Date column in prompt table has a datatype of float. UTCTime and DateCollected are both varchar(20)
The error is:
Msg 242, Level 16, State 3, Line 274
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Here is the function:
[dbo].[fn_GetGPtime] (#UTCtime datetime)
returns varchar(50)
AS
BEGIN
return (DATEPART (WEEKDAY, #UTCtime) - 1) * 86400 ---day
+ DATEPART (HOUR, #UTCtime) * 3600 ---hour
+ DATEPART (MINUTE, #UTCtime) * 60 ----minutes
+ DATEPART (SECOND, #UTCtime) ---second
+ (DATEPART (MILLISECOND, #UTCtime)) * 0.001 ---ms
+ (DATEPART (MICROSECOND, #UTCtime)) * 0.000001 ---us
+ 16 ----leap seconds
end;
To get an idea of the data itself:
How do I fix this issue?
Your error message could mean two different things: that you have non-convertible data in some cells, or that field's data are not convertible to datetime at all.
You can use try_convert instead of convert to figure out which it is. It will solve your problem if you have a few completely unusable values (i.e. bad data); you'll get nulls for bad data and good conversion for good data. If the overall conversion is never going to work you'll get all nulls and you'll know it isn't just a few bad values.
Another thing you could try is converting from float to numeric before converting to datetime. I find that float formatted data are awful for conversions and converting to numeric can remove many issues. You'd have something like convert(datetime, convert(numeric(18,2), UTCTime))
Use convert instead of cast. When using convert, you can specify the format of the string representing the date.
Once you've converted DateCollected to datetime, you can cast a.UTCTime to datetime and add them together:
Insert into prompt(ID,Date)
select ROW_NUMBER() over (order by b.IDLoc),
[dbo].[fn_GetGPtime](convert(datetime, DateCollected, 101) + cast(a.UTCTime as datetime))
from Img a inner join Tloc b on a.Filename=b.filename
order by b.IDLoc
(assuming a.UTCTime is either varchar or time)
What worked for me, solving this error on an input line such as
SELECT CAST(N'2003-12-01 14:20:47.000' AS DateTime) AS result
Msg 242 Level 16 ...
is the magic instruction:
SET DATEFORMAT ymd;
I have below sample data:
03202012 as date but the column datatype is Varchar.
I want to convert it to 2012-03-20 00:00:00.000 as Datetime.
I tried using
CAST(CONVERT(CHAR(10), Column, 101) AS DATETIME)
But I get an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Complete code snippet to test:
DECLARE #Column VARCHAR(MAX) = '03202012'
SELECT CAST(CONVERT(CHAR(10), #Column, 101) AS DATETIME)
Use yyyyMMdd format, that always works:
DECLARE #myDateString varchar(10) = '03202012';
SELECT cast( substring(#myDateString, 5, 4)+
substring(#myDateString, 1, 2)+
substring(#myDateString, 3, 2) AS datetime);
I found below script help me solved my concern.
SELECT convert(datetime, STUFF(STUFF('31012016',3,0,'-'),6,0,'-'), 105)
Result: 2016-01-31 00:00:00.000
Thanks all for the effort. :D
In MySQL, you can use the STR_TO_DATE function to convert a string to a date. For your example, it would look like this
STR_TO_DATE("03-02-2012", "%m-%d-%Y");
Note that the format part of the string must match the format part of the date.
Edit: Just found out this is for SQL Server, but I assume this will work there as well.
I am facing issue while querying for some data from SQL. The column datatype is varchar which has datetime stamp as part of its name, like DUMMY2_20140713.pdf.
Want to search for files between week date duration.so trying to convert part of file name to date as below:
select file_name,file_name
from t_pdf_weekly_violation
where CONVERT(datetime, SUBSTRING(file_name, CHARINDEX('_', file_name) + 1, 8), 112) between 20150506 and 20150513;
But it is throwing exception..Please find stack trace below:
com.microsoft.sqlserver.jdbc.SQLServerException: Arithmetic overflow
error converting expression to data type datetime. at
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
at
com.microsoft.sqlserver.jdbc.SQLServerResultSet$FetchBuffer.nextRow(SQLServerResultSet.java:4700)
at
com.microsoft.sqlserver.jdbc.SQLServerResultSet.fetchBufferNext(SQLServerResultSet.java:1683)
at
com.microsoft.sqlserver.jdbc.SQLServerResultSet.next(SQLServerResultSet.java:956)
at databaseconnection.ConnectionURL.main(ConnectionURL.java:36)
Have any one idea on this?
Thanks in advance
There is no need to convert substring to Datetime, just remove CONVERT(datetime
SELECT file_name,file_name
FROM t_pdf_weekly_violation
WHERE SUBSTRING(file_name, CHARINDEX('_', file_name) + 1, 8) between 20150506 and 20150513;
Sample SQL FIDDLE
Alternate Solution
If you want to use CONVERT(datetime, then you have to convert your all dates
SELECT file_name,file_name
FROM t_pdf_weekly_violation
WHERE CONVERT(datetime,SUBSTRING(file_name, CHARINDEX('_', file_name) + 1, 8),112)
between CONVERT(datetime,'20150506',112) and CONVERT(datetime,'20150510',112);
Sample SQL FIDDLE
It is working when I changed return type datetime to char, like
SELECT file_name,file_name
FROM t_pdf_weekly_violation
WHERE CONVERT(char(8),SUBSTRING(file_name, CHARINDEX('_', file_name) + 1, 8),112)
between CONVERT(char(8),'20150506',112) and CONVERT(char(8),'20150510',112);
I have a column abc varchar(100) with data like 2011-09-26 16:36:57.810000
I want to convert this column to DATETIME...
But doing a
Convert(DATETIME, abc,120)
is giving this error:
Conversion failed when converting date and/or time from character string.
Can any one please help me convert my varchar format to datetime in SQL Server 2008?
Thanks in advance
You can use style 121 but you can have only 3 digits for milliseconds (i.e yyyy-mm-dd hh:mi:ss.mmm(24h)) format.
declare #abc varchar(100)='2011-09-26 16:36:57.810'
select convert(datetime,#abc,121)
So you can sort it out by limiting the varchar field to 23 characters before converting as:
declare #abc varchar(100)='2011-09-26 16:36:57.810000'
select convert(datetime,convert(varchar(23),#abc),121)
Or use the Left() function to get first 23 characters as:
select convert(datetime,left(#abc,23),121)
Try to avoid storing date as string.
In case you need 6 digits precision use DATETIME2
SELECT CONVERT(DATETIME2, '2016-08-09T08:08:50.358000', 126) as MSSQLDateTime2
SELECT CONVERT(DATETIME, '2016-08-09T08:08:50.358', 126) as MSSQLDateTime
SQL Server only supports 3 decimal places for milliseconds, so the following will work:
Convert(DATETIME, SUBSTRING(abc, 0, 24) ,120)
Based on GBrian's answer, I came up with:
CONVERT(DATETIME, CONVERT(DATETIME2, abc, 126))
I haven't benchmarked how this stacks up against the substring-based solutions.
Assuming we have the following string variables:
DECLARE #d VARCHAR(100) = '2020-04-06T04:35:07.9490051Z' -- 7 digits nanoseconds
DECLARE #d1 VARCHAR(100) = '2020-04-05T15:00:00Z' -- simple: without nanoseconds
I came up to the solution using CAST operator:
SELECT CAST(LEFT(#d,19) + 'Z' AS DATETIME) -- outputs: 2020-04-06 04:35:07.000
SELECT CAST(LEFT(#d1,19) + 'Z' AS DATETIME) -- outputs: 2020-04-05 15:00:00.000
I need to Subtract the datetime type data for example from a column like:
datetime
20/03/2013:03:17:43
20/03/2013:03:17:43
20/03/2013:03:17:44
20/03/2013:03:17:44
20/03/2013:03:17:44
20/03/2013:03:17:44
I am using SQL Server R2 2008; with my Query like:
SELECT basescore,
MAX(datetime) - MIN(datetime)
FROM log
GROUP BY basescore
But all the time it gives me an error:
Msg 8117, Level 16, State 1, Line 3
Operand data type varchar is invalid for subtract operator.
Can somebody help me solving this error? Thanks in advance!
You column is of a VarChar type. Please use conversion in conjunction with DATEDIFF function.
SELECT basescore, DATEDIFF(DD,MAX(CAST([datetime] as datetime)), MIN(CAST([datetime] as datetime))) FROM log GROUP BY basescore
But I agree - if the column contains datetime data - it should be of a datetime type.
UPDATE: You have a semicolon between date and time. If you do not have control over imported data you can modify the above query as
SELECT basescore, DATEDIFF(DD,MAX(CAST(STUFF([datetime],11,1,' ') as datetime)), MIN(CAST(STUFF([datetime],11,1,' ') as datetime))) FROM log GROUP BY basescore
But as you see it's getting more and more involved. It would be much easier and safer if the column were of datetime type.
"Operand data type varchar is invalid for subtract operator" the data type varchar is invalid .. so use CAST to convert data type as datetime
SELECT basescore,DATEDIFF(DD,MAX(datetime),MIN(datetime))FROM log GROUP BY basescore
you have to use datediff function
http://msdn.microsoft.com/en-us/library/aa258269(v=sql.80).aspx
Thanks