需要使用 ms sql 将时间转换为数字

Need to convert time into number using ms sql

我有一个名为 DATA 的 table,它有以下两列:-

TaughtDistinct - varchar

ValueofTaught - 数字(2,2)

Taught distinct 保存时间,例如 07:30 但我需要在 ValueofTaught 列中将其设置为 7.5。

我无法解决问题,我已经尝试了以下查询:-

select * from CQData2

--Add temporary column TempValueOfTaught
alter table CQData2 add TempValueOfTaught Numeric(5,2)


--Update temporary column with values from ValueOfTaught
update CQData2 set TempValueOfTaught = ValueOfTaught


--Set ValueOfTaught to null
update CQData2 set ValueOfTaught = NULL


--change data type of ValueOfTaught to numeric
alter table CQData2 alter column ValueOfTaught NUMERIC(5,2)


--Ensure TempValueOfTaught is returning numeric values only
Select * from CQData2 where ISNUMERIC(TempValueOfTaught)=0


--Update ValueOfTaught using TempValueOfTaught values
update CQData2 set ValueOfTaught = Cast(TempValueOfTaught as numeric (5,2))

假设您的数据在格式上与您的示例一致(尤其是个位数小时的前导零),这是一个快速的概念证明...

DECLARE @MyTime varchar(max)

SET @MyTime = '07:30'

SELECT 
    @MyTime, 
    CONVERT(real, LEFT(@MyTime, 2)) + (CONVERT(real, RIGHT(@MyTime, 2)) / 60.0) AS [ValueOfTaught]

更新...

UPDATE 
    CQData2 
SET 
    ValueofTaught = ROUND(CONVERT(real, LEFT(TaughtDistinct, 2)) + (CONVERT(real, RIGHT(TaughtDistinct, 2)) / 60.0), 2)
WHERE
    ValueofTaught IS NULL

请注意,我在代码中将数据类型从 numeric(2,2) 更改为 real。 Precision 和 Scale 都设置为 2 的 numeric 数据类型将永远无法保存大于或等于 1 的值。

这是整个交易的 SQL Fiddle,包括在 OP 中可见的尽可能多的示例数据。

您还可以使用新的时间数据类型来更灵活地处理您的格式:

DECLARE @MyTime1 varchar(max) = '07:30'
DECLARE @MyTime2 varchar(max) = '7:30'
DECLARE @MyTime3 varchar(max) = '7:30:00'

SELECT @MyTime1 as style1 
      ,DATEPART(HOUR,CONVERT(time(0),@MyTime1))
       + DATEPART(MINUTE,CONVERT(time(0),@MyTime1))/CONVERT(real,60.0) AS [Hours1]
      ,@MyTime2 as style2, 
      ,DATEPART(HOUR,CONVERT(time(0),@MyTime2))
       + DATEPART(MINUTE,CONVERT(time(0),@MyTime2))/CONVERT(real,60.0) AS [Hours2]
      ,@MyTime3 as style3, 
      ,DATEPART(HOUR,CONVERT(time(0),@MyTime3))
       + DATEPART(MINUTE,CONVERT(time(0),@MyTime3))/CONVERT(real,60.0) AS [Hours3]

结果:

style1   Hours1   style2   Hours2   style3   Hours3
07:30    7,5      7:30     7,5      7:30:00  7,5