如何将varchar转换为时间hh:mm

问题描述 投票:1回答:3

我有代表军事时代的varchars:

a 2130 -- 21 hours
b 103 -- 1 hour
c 10  -- 10 minutes
d 1  -- 1 minutes

左边两个字符总是代表分钟。在示例c和c中,10和1之上总是分钟。例子b 103有三个字符。在这种情况下,1是小时03分钟。

如何将其转换为时间hh:mm格式?

sql-server tsql sql-server-2008-r2 type-conversion
3个回答
3
投票

一个选项是使用Format()

Declare @YourTable table (SomeCol int)
Insert into @YourTable values
 (2130)
,(103)
,(10)
,(1)

Select SomeCol
      ,TimeValue = format(SomeCol,'00:00')
 From  @YourTable

返回

SomeCol TimeValue
2130    21:30
103     01:03
10      00:10
1       00:01

编辑 - 请求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

0
投票

您可以使用列值和case语句的长度来尝试以下操作。

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

0
投票

雅各布,美好的一天,

请检查此解决方案是否适合您:

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,我在评论中注意到了新的信息。好像你使用SQL Server 2008R2和TIMEFROMPARTS将无法在SQL Server2008r2上工作(仅从2012年开始)...我将在一秒钟内编辑答案

注意!我强烈建议您重新考虑一下您的数据库设计。请阅读我上面写的评论以获取更多信息

更新:

-- 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
© www.soinside.com 2019 - 2024. All rights reserved.