How to convert varchar to time hh:mm - sql-server

I have varchars representing military times:
a 2130 -- 21 hours
b 103 -- 1 hour
c 10 -- 10 minutes
d 1 -- 1 minutes
the left two characters always represent minutes. In example c and c above 10 and 1 are always minutes. example b 103 has three characters. 1 is hour 03 is minute in this case.
How do I convert this into time hh:mm format?

One option is use to use Format()
Example
Declare #YourTable table (SomeCol int)
Insert into #YourTable values
(2130)
,(103)
,(10)
,(1)
Select SomeCol
,TimeValue = format(SomeCol,'00:00')
From #YourTable
Returns
SomeCol TimeValue
2130 21:30
103 01:03
10 00:10
1 00:01
EDIT - Requested EDIT for 2008
Declare #YourTable table (SomeCol int)
Insert into #YourTable values
(2130)
,(103)
,(10)
,(1)
Select SomeCol
,TimeValue = stuff(right('0000' + left(SomeCol, 4),4), 3, 0, ':')
From #YourTable

You can try the following using length of column value and case statement.
Declare #YourTable table (SomeCol int)
Insert into #YourTable values
(2130)
,(103)
,(10)
,(1)
Select
case LEN(SomeCol)
when 4 then SUBSTRING('2130', 1, 2) + ':' + SUBSTRING('2130', 3, 2)
when 3 then '0' + SUBSTRING('103', 1, 1) + ':' + SUBSTRING('103', 2, 2)
when 2 then '00:' + CONVERT(Varchar(5), SomeCol)
else '00:0' + CONVERT(Varchar(5), SomeCol)
end as TimeValue
from #YourTable

Good day Jacob,
Please check if this solution fit you:
Declare #YourTable table (SomeCol int)
Insert into #YourTable values
(2130)
,(103)
,(10)
,(1)
--Select SomeCol,TimeValue = format(SomeCol,'00:00'), SQL_VARIANT_PROPERTY (format(SomeCol,'00:00'),'BaseType')
--From #YourTable
SELECT CONVERT(TIME(0),TIMEFROMPARTS(ROUND(SomeCol/100,0), SomeCol%100,0,0,0))
FROM #YourTable
Ops, I notice new information in the comments. Seems like you use SQL Server 2008R2 and TIMEFROMPARTS will not work on SQL Server2008r2 (only starting with 2012)...I will edit the answer in a second
Note! I highly recommend to re-think about your database design.Please read the comment I wrote above for more information
Update:
-- For old servers please check if one of these this fit you
SELECT --RIGHT('00' + CONVERT(VARCHAR(2),ROUND(SomeCol/100,0)),2),RIGHT('00' + CONVERT(VARCHAR(2),SomeCol%100),2),
CONVERT(TIME(0),RIGHT('00' + CONVERT(VARCHAR(2),ROUND(SomeCol/100,0)),2) + ':' + RIGHT('00' + CONVERT(VARCHAR(2),SomeCol%100),2))
FROM #YourTable

Related

Dynamic SQL to randomize all datetime columns in a database

I'm having trouble figuring out how to use a dynamic SQL Server query to change the datetime fields in my database, called OnlineStore, to be random and in the current year.
It should be noted that this relates to homework. My class is fairly unstructured, so I'm having a hard time knowing where to go from here.
My question is: How can I write a dynamic SQL Server query that may use loops or table variables and takes the 2 datetime columns in my database (Product.LastOrderDate, Orders.OrderDate) and assigns each row a random date in the current year?
This is what I have so far. I'm open to any changes.
Declare #SQL varchar(max) = '
Declare #D1 float = cast(cast(''2017-01-01 00:00:00'' as datetime) as float);
Declare #D2 float = cast(cast(''2017-12-31 23:59:59'' as datetime) as float);
Based on this answer I came up with the following. It randomly adds n seconds to the date 2017-01-01 capped at the number of seconds in 2017.
The first bit is just me generating a table with 50 rows, all 2017-01-01.
You'll want to focus on the parts from update on...
if object_id('tempdb..#test') is not null drop table #test
create table #test (orderDate datetime)
-- add 50 rows to test table
;with x as
(
select 1 as t
union all
select t+1
from x
)
insert into #test
select top 50 '2017-01-01'
from x
option(maxrecursion 50)
--select * from #test
update t
set OrderDate = dateadd(second,ABS(CHECKSUM(NewId())) % datediff(second,'2017-01-01 00:00:00','2017-12-31 23:59:59'),'2017-01-01 00:00:00')
from #test t
select * from #test
Based on this answer: https://stackoverflow.com/a/18408615
This gets you almost all the way there for generating a random date, I capped the days at 28 due to February being February.
select cast('2017-' + CAST(ABS(Checksum(NEWID()) % 12) + 1 AS varchar(2)) + '-' + CAST(ABS(Checksum(NEWID()) % 28) + 1 AS varchar(2)) as date)
You can adapt this to fit your needs.

Get the right number of a value in SQL Server using substring

I have this data in my SQL Server:
1/2
1/4
2/23
12/13
1/10
...
I need to change these to 002,004,023,013,010,..
I just need to select the end (RIGHT) part number of my value. I got the LEFT part using this code before:
RIGHT('000' + LEFT(SheetNumber, CHARINDEX('/', SheetNumber) - 1), 3)
Try this,
SELECT Right('000' + RIGHT(SheetNumber,LEN(SheetNumber) - CHARINDEX('/',SheetNumber) ), 3)
OR
SELECT RIGHT(REPLACE(#SheetNumber,'/','/000'),3)
Your were almost there
Declare #YourTable table (SheetNumber varchar(50))
Insert Into #YourTable values
('1/2'),
('1/4'),
('2/23'),
('12/13'),
('1/10')
Select right('000'+substring(SheetNumber,CHARINDEX('/',SheetNumber) + 1,10),3)
From #YourTable
Returns
(No column name)
002
004
023
013
010
First you need to get the right part like this :
declare #table table (SheetNumber varchar(10))
insert into #table values ('1/2')
insert into #table values ('2/23')
select Right(SheetNumber, len(SheetNumber) - CHARINDEX('/',SheetNumber)) from #table
This will give you this :
2
23
Now build on this to pad 0 in front of it
declare #table table (SheetNumber varchar(10))
insert into #table values ('1/2')
insert into #table values ('2/23')
select Right('000' + Right(SheetNumber, len(SheetNumber) - CHARINDEX('/',SheetNumber)), 3) from #table
and that will give you this :
002
023

Converting string with minutes over 60 into time datatype causes an error

Declare #Data Table (Working_Hours nvarchar(10)); datatable
insert into #Data (working_hours) select '0:10'; insertion values
insert into #Data (working_hours) select '1:90';
insert into #Data (working_hours) select '0:10';
insert into #Data (working_hours) select '0:10';
--select working_hours from #Data; *this state work*
--select #data as lion ; this state also work
select
convert(int, (datepart(hour, CONVERT(time, q1.working_hours)) * 60) +
DATEPART(MINUTE, CONVERT(time, q1.working_hours))) as lion
from #Data q1;
results in a conversion error - I want to convert min from nvarchar and then convert into int to calculate sum in sap report
How can denominate the work through way..
Assuming that's just hours and minutes with problems with the data (90 minutes), you can do this without using time -datatype which of course doesn't allow that kind of time:
select
convert(int, left(working_hours, charindex(':', working_hours)-1)) * 60 +
convert(int, substring(working_hours, charindex(':', working_hours)+1,10))
from
#data
Will work with SQL Server 2012+
LiveDemo
WITH cte AS
(
SELECT [working_hours] = REPLACE(q1.working_hours, ':', '.')
FROM #Data q1
)
SELECT
[lion] = PARSENAME(working_hours, 2) * 60 + PARSENAME(working_hours, 1)
FROM cte
One way or another you need to get chunks of data. So one fancy way to do it is to use PARSENAME

Convert date in text format to datetime format in T-SQL

I have a client supplied file that is loaded in to our SQL Server database. This file contains text based date values i.e. (05102010) and I need to read them from a db column and convert them to a normal date time value = '2010-05-10 00:00:00.000' as part of a clean-up process.
Any guidance would be greatly appreciated.
one way by using
CONVERT(datetime,RIGHT(Column,4) + left(Column,4))
example
declare #s char(8)
select #s = '05102010'
select CONVERT(datetime,RIGHT(#s,4) + left(#s,4))
Try:
SELECT
CONVERT(datetime, RIGHT(YourColumn,4)
+LEFT(YourColumn,4)
) AS ProperDateTime
FROM...
working example:
DECLARE #YourTable table (StringDate char(8))
INSERT #YourTable VALUES ('05102010')
INSERT #YourTable VALUES ('03182010')
SELECT
CONVERT(datetime, RIGHT(StringDate,4)
+LEFT(StringDate,4)
) AS ProperDateTime
FROM #YourTable
OUTPUT:
ProperDateTime
-----------------------
2010-05-10 00:00:00.000
2010-03-18 00:00:00.000
(2 row(s) affected)
Quick and dirty:
SELECT
CONVERT(DATETIME,
SUBSTRING(col, 1, 2)
+ '/' + SUBSTRING(col, 3, 2)
+ '/' + SUBSTRING(col, 5, 4))

Converting an integer to a 0-padded string

In SQL Server 2008, I want to represent an integer as a 3-character string - so:
3 becomes '003'
5 becomes '005'
107 becomes '107'
How can I do this?
/* Method 1 Using RIGHT function */
SELECT RIGHT('000' + CAST(NumericColumn AS VARCHAR(3)), 3) PaddedCnumericColumn
FROM MyTable
/* Method 2 Using RIGHT AND REPLICATE function */
SELECT RIGHT(REPLICATE('0', 3) + CAST(NumericColumn AS VARCHAR(3)), 3) PaddedCnumericColumn
FROM MyTable
You can try this
DECLARE #Table TABLE(
Val INT
)
INSERT INTO #Table (Val) SELECT 1
INSERT INTO #Table (Val) SELECT 10
INSERT INTO #Table (Val) SELECT 100
SELECT REPLICATE('0',3 - LEN(CAST(Val AS VARCHAR(3)))) + CAST(Val AS VARCHAR(3))
FROM #Table
WHERE ABS(Val) < 1000

Resources