SQL convert data type - sql

I have two column with "text" datatype, i need to convert the the entire data in the first column to "datetime" data type, and the second column to "decimal(10,3)" data type.
Example of the current data:
first column: 20090901000005 covert to 2009/08/01 00:00:05
second column: .125 convert to 00.125
Any one can help Please :)

You can use something like this:
select cast(cast(col1 as varchar(8)) as datetime) +
cast(left(right(cast(col1 as varchar(14)), 6), 2) + ':' +
substring(right(cast(col1 as varchar(14)), 6), 2, 2) + ':' +
right(right(cast(col1 as varchar(14)), 6), 2) as datetime) newDate,
cast(cast(col2 as varchar(10)) as decimal(10, 3)) newDecimal
from yourtable
See SQL Fiddle with Demo

I would do it as follows:
SELECT
CONVERT(DATETIME,
(SUBSTRING(dateValue, 1, 8) + ' ' +
SUBSTRING(dateValue, 9, 2) + ':' +
SUBSTRING(dateValue, 11, 2) + ':' +
SUBSTRING(dateValue, 13, 2))) as 'dateValue',
CONVERT(DECIMAL(10, 3), decimalValue) as 'decimalValue'
FROM text_table

You can use left and right to split string into parts. Then use convert function to convert it to date. ODBC canonical (120) format is: yyyy-mm-dd hh:mi:ss
CONVERT(datetime,
left( firstcol, 4 ) + '-' +
left( right( firstcol, 10 ) ,2 ) + '-' +
left( right( firstcol, 8 ) ,2 ) + ' ' +
left( right( firstcol, 6 ) ,2 ) + ':' +
left( right( firstcol, 4 ) ,2 ) + ':' +
right( firstcol, 2 )
, 120)
For second column:
CONVERT( float, right( secondcol, 3 ) ) / 1000

Related

Converting NVARCHAR to SMALLDATETIME on SQL SERVER 2008

I'm currently working on updating company database in which on one of the tables the CreateDt is in the nvarchar(20) type and stores dates in the following ways:
12 May 12
29/03/2011
9/24/2012
29/01/2001 08:51:56
There are 17,000 rows.
So I'm currently working on code in which I will be able to convert these dates all into the one format such as DD-MM-YYYY.
However I'm struggling to find anything suitable.
So far I have tried:
WITH CreateDt1
AS
(
SELECT '14 DECEMBER 12' AS CreateDt1
UNION ALL
SELECT '13/10/2005'
UNION ALL
SELECT '12/14/2012'
UNION ALL
SELECT '24/05/2002 09:28:58'
UNION ALL
SELECT '28/02/2011'
)
SELECT
CreateDt1,
CASE WHEN ISDATE(CreateDt1) = 1
THEN CAST(CreateDt1 AS datetime)
ELSE
CASE WHEN SUBSTRING(CreateDt1, 3, 1) = '/'
THEN
CASE WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + RIGHT (CreateDt1, 4)) = 1
THEN CAST(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1 , 2) + '/' + RIGHT (CreateDt1, 4) AS datetime)
END
END
END AS NewDate
FROM fct_Project;
However this returns null values for dates such as 29/01/2001 08:51:56.
Try add LEFT function in RIGHT to your query in case clause like:
CASE WHEN ISDATE(CreateDt1) = 1
THEN CAST(CreateDt1 AS datetime)
ELSE
CASE WHEN SUBSTRING(CreateDt1, 3, 1) = '/'
THEN
CASE WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + RIGHT (LEFT(CreateDt1,10), 4)) = 1
THEN CAST(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1 , 2) + '/' + RIGHT (LEFT(CreateDt1,10), 4) AS datetime)
END
END
END AS NewDate
I've just edited your code by adding a few lines, hope it will help.
Keep in mind, that it does not solve problem of 10/11 and 11/10 cases.
WITH CreateDt1
AS
(
SELECT '14 DECEMBER 12' AS CreateDt1
UNION ALL
SELECT '13/10/2005'
UNION ALL
SELECT '12/14/2012'
UNION ALL
SELECT '24/05/2002 09:28:58'
UNION ALL
SELECT '28/02/2011'
)
SELECT
CASE WHEN ISDATE(CreateDt1) = 1
THEN CAST(CreateDt1 AS datetime)
ELSE
CASE WHEN SUBSTRING(CreateDt1, 3, 1) = '/'
THEN
CASE WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + RIGHT (CreateDt1, 4)) = 1
THEN CAST(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1 , 2) + '/' + RIGHT (CreateDt1, 4) AS datetime)
WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + LEFT((RIGHT (CreateDt1, 13)),4) ) = 1
THEN CAST ( (SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + LEFT((RIGHT (CreateDt1, 13)),4) ) AS DATETIME)
END
END
END AS NewDate
FROM CreateDt1;

SQL Server : converting varchar field to date

I have in my table a varchar column with bunch of dates in the following format dd-MM-yyyy
31-12-2018
01-01-2019
02-01-2019
I need to write a date based query that gets all the dates before 01-01-2019.
I have tried using both CAST and CONVERT to convert these table values without luck.
Using CAST, my code is below:
SELECT
CAST('''' + SUBSTRING(arc_billed_to_date, 4, 2) + '-' + SUBSTRING(arc_billed_to_date, 1, 2) + SUBSTRING(arc_billed_to_date, 6, 5)+ '''' AS date),
CAST('''' + SUBSTRING(arc_billed_to_date, 7, 5) + '-' + SUBSTRING(arc_billed_to_date, 1, 2) + '-' + SUBSTRING(arc_billed_to_date, 4, 2) + '''' AS date),
CAST('''' + SUBSTRING(arc_billed_to_date, 7, 5) + '-' + SUBSTRING(arc_billed_to_date, 4, 2) + '-' + SUBSTRING(arc_billed_to_date, 1, 2) + '''' AS DATE),
CONVERT(DATE, '12-31-2018') AS x
FROM
wkpol
Using Convert
select Convert(datetime,'''' + SUBSTRING(arc_billed_to_date,7,5) + '-' + SUBSTRING(arc_billed_to_date,4,2) + '-' + SUBSTRING(arc_billed_to_date,1,2)+ '''',105) as x from wkpol
The error I get is
Conversion failed when converting date and/or time from character string.
Any help is appreciated.
SELECT *
FROM wkpol
WHERE convert(date, arc_billed_to_date, 103) < convert(date, '01/01/2019');
Well you are going to get many blames for using varchar field for date. Anyway, assuming it is a matter of another thread you can do the conversion like:
select * from myTable
where cast(right(arc_billed_to_date,4) +
substring(arc_billed_to_date,4,2) +
left(arc_billed_to_date,2) as date) < '20190101';
You wouldn't be using any index either.
In addition to Sean's comments, you can also set the DateFormat as DMY
Example
Declare #YourTable table (SomeCol varchar(50))
Insert Into #YourTable values
('31-12-2018')
,('01-01-2019')
,('02-01-2019')
Set DateFormat DMY
Select AsDate = try_convert(date,SomeCol)
From #YourTable
Returns
AsDate
2018-12-31
2019-01-01
2019-01-02

Date Conversion of yymmddhhmm.yymmddhhmm in SQL

I'm getting this type of data in DateandTime Column in SQl.
1803301611.1803301611
Format is yymmddhhmm.yymmddhhmm and I have to convert this data in a date format.
The DateandTime Column date type is Varchar(5)
I don't think the format of your time string can be directly converted by SQL Server. But, we can try to piece together into a format which can be. This is the closest I could come, and it required prepending a 20 in front of the year to make a full 4 digit century:
SELECT
col AS input,
CONVERT(datetime, '20' + SUBSTRING(col, 1, 2) + '-' + SUBSTRING(col, 3, 2) + '-' +
SUBSTRING(col, 5, 2) + ' ' + SUBSTRING(col, 7, 2) + ':' +
SUBSTRING(col, 9, 2), 120) AS output
FROM yourTable;
Demo
We ideally should have been able to use mask 20 without the century, but I could not get it to work.
You can do :
select *, cast(concat(cast(left(col, 6) as date), ' ',stuff(right(col, 4), 3, 0, ':')
) as datetime
) as newdatetime
from table t;

Convert four Digit number into hour format SQL

I have looked into Cast and Convert, but I cannot find a way to do this. I need to convert four digits into an hour format. For instance, 0800 would become 8:00 or 1530 would become 15:30. I cannot use functions, I'm using a InterSystem's CacheSQL. Any suggestions? Thanks in advance!
EDIT:
If it is any more convenient, I can just divide the four digits by one hundred to get values like 15 from original 1500, or 8.30 from 0830. Does this make converting to hour:minute format easier?
For CacheSQL, you can do this:
SELECT {fn TRIM(LEADING '0' FROM LEFT(col_name, 2) || ':' || RIGHT(col_name, 2)) }
FROM table_name
In SQL Server 2008, given data that looks like
create table #data
(
HHMM int not null ,
)
insert #data values ( 0800 )
insert #data values ( 0815 )
insert #data values ( 1037 )
insert #data values ( 2359 )
You can say:
select * ,
strTime = right( '0' + convert(varchar, HHMM / 100 ) , 2 )
+ ':'
+ right( '0' + convert(varchar, HHMM % 100 ) , 2 ) ,
myTime = convert(time ,
right( '0' + convert(varchar, HHMM / 100 ) , 2 )
+ ':'
+ right( '0' + convert(varchar, HHMM % 100 ) , 2 ) ,
120
)
from #data
Other SQL implementations likely have similar functionality.
In earlier versions of SQL Server that lack the time datatype, just use datetime, thus:
select * ,
strTime = right( '0' + convert(varchar, HHMM / 100 ) , 2 )
+ ':'
+ right( '0' + convert(varchar, HHMM % 100 ) , 2 ) ,
myTime = convert(datetime,
right( '0' + convert(varchar, HHMM / 100 ) , 2 )
+ ':'
+ right( '0' + convert(varchar, HHMM % 100 ) , 2 ) ,
120
)
from #data
You'll get a datetime value that is 1 Jan 1900 with the desired time-of-day.
Well, if it is something like Oracle you might have a try with the to_date() function.
Read more here.
Example:
SELECT to_date(yourColumn, 'HH24MI') FROM ...
EDIT (why? see comments): If necessary (I'm actually not familiar with Oracle) you can wrap another function like TIME() around it.
SELECT TIME(to_date(yourColumn, 'HH24MI')) FROM ...
Read more about TIME() here.
</EDIT>
In MySQL the equivalent would be the STR_TO_DATE() function:
SELECT STR_TO_DATE(yourColumn, '%H%i') FROM ...
Read about STR_TO_DATE() and its parameters under the DATE_FORMAT() function.
left( case when (EndTime / 100) < 10 then ('0'+ convert(varchar, EndTime / 100 )) else convert(varchar, EndTime / 100 ) end, 2 )
+ ':'
+ right( '0' + convert(varchar, EndTime % 100 ) , 2 )

How can I find out which data won't cast?

I have a SQL table with a date field defined as char(8), or 20090609, and a time field defined as char(4), or 1230. I am moving this data into another table and I want to combine the two fields and put them in a smalldatetime field in the new table. My query is like this:
INSERT NewTable(eventdate)
SELECT
CAST((datecol + ' ' + substring(timecol, 1, 2) + ':' + substring(timecol, 3, 2)) as smalldatetime)
FROM OldTable
When I run this, I get an error:
The conversion of char data type to
smalldatetime data type resulted in an
out-of-range smalldatetime value.
I've tried checking len(datecol) and len(timecol) to make sure that they are at least the correct number of characters. I have no idea how I can find the offending data, any suggestions? The database is SQL2000 and I'm using SMO 2008.
Try this:
SELECT datecol, timecol
FROM OldTable
WHERE ISDATE(datecol + ' ' + substring(timecol, 1, 2) + ':' + substring(timecol, 2, 2)) = 0
That will show you which rows cannot be converted successfully.
It is probably out of the range of acceptable smalldatetime values
January 1, 1900, through June 6, 2079
EDIT On closer inspection I think the substring parameters for the second portion of the time may be incorrect (which may be the whole problem) updated below to reflect substring(timecol, 3, 2)
New Approach this sql does assume that all dates are 8 characters in length, and all times are 4.
Select SubString(DateCol, 1, 4) as tehYear,
Substring(DateCol, 5,2) as tehMonth,
SubString(DateCol, 7,2) as tehDay,
SubString(TimeCol, 1,2) as tehHour,
Substring(TimeCOl, 3,4) as tehMinute,
*
from OldTable
where
(SubString(DateCol, 1,4) > 9999 or SubString(DateCol, 1,4) < 1753)
OR (Substring(DateCol, 5,2) > 12 or Substring(DateCol, 5,2) < 1)
OR (SubString(DateCol, 7,2) > 31 or SubString(DateCol, 7,2) < 1)
OR (SubString(TimeCol, 1,2) > 23 or(SubString(TimeCol, 1,2) < 0)
OR (Substring(TimeCOl, 3,4) > 59 or Substring(TimeCOl, 3,4) <0)
Try casting to datetime and seeing if there are any dates that fall outside of that range to identify your problem data.
SELECT
CAST((datecol + ' ' + substring(timecol, 1, 2) + ':' + substring(timecol, 3, 2))
as datetime)
FROM OldTable
Where CAST((datecol + ' ' + substring(timecol, 1, 2)
+ ':' + substring(timecol, 3, 2)) as datetime)
> Cast('06/06/2079' as datetime) or CAST((datecol + ' '
+ substring(timecol, 1, 2) + ':' + substring(timecol, 3, 2)) as datetime)
< Cast('01/01/1900' as datetime)
If you run the query in query analyzer it should tell you what row the error occured!