我有一个名为DATA的表,它有两列: -
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))
答案 0 :(得分:3)
假设您的数据格式与您的示例一致(尤其是单位数小时的前导零),这是一个快速的概念证明...
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
。精度和比例都设置为2的numeric数据类型永远不能保存大于或等于1的值。
这里是整个交易的SQL Fiddle,包括OP中可见的样本数据。
答案 1 :(得分:2)
您还可以使用新的time-Datatype更灵活地使用Format:
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