【问题标题】:SQL Server: convert an int value into a time valueSQL Server:将 int 值转换为时间值
【发布时间】:2017-12-08 15:08:32
【问题描述】:

在 SQL Server 查询中,我想将 int 转换为时间。

int 表示小时和分钟 (hhmm)。

例如:

1945 --> 19:45
30 --> 00:30
1 --> 00:01

使用您的解决方案修改后,此查询应返回 true、true、true。

declare @int1 int = 0
declare @int2 int = 35
declare @int3 int = 1810

select 
    @int1 = '00:00', @int2 = '00:35', @int3 = '18:10'

【问题讨论】:

  • 模算术是你的朋友。这也是。 docs.microsoft.com/en-us/sql/t-sql/functions/…
  • stuff(stuff('0000', 5 - len(@int), len(@int), @int), 3, 0, ':')
  • 值得注意的是,SELECT @int1 = '00:00' 不会返回 TRUE,它会导致转换错误,因为 SQL Server 试图将 varchar'00:00' 分配给数据类型的变量int。要获得 TRUE/FALSE 响应,您需要使用 CASE 表达式。
  • 这是时钟(最多 23:59)还是小时总和?

标签: sql sql-server type-conversion


【解决方案1】:

试试:

WITH Times AS(
    SELECT *
    FROM (VALUES (1945),(30),(1)) AS V(IntTime))
SELECT IntTime,
       CONVERT(time,STUFF(RIGHT('0000' + CONVERT(varchar(5),IntTime),4),3,0,':')) As TimeTime
FROM Times;

【讨论】:

  • 谢谢,正是我需要的。
【解决方案2】:
declare @int1 int = 0
declare @int2 int = 35
declare @int3 int = 1805

declare @my_integer_value int

set @my_integer_value = @int1 -- Change to @int2 or @int3 as required.

select convert(char(8),convert
    (DATETIME,cast(@my_integer_value/100 as varchar(2))+':'+cast( @my_integer_value % 100 as varchar(2))+':00'
    ,108),108)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 2016-12-20
    相关资源
    最近更新 更多