简体   繁体   English

SQL 将 Nvarchar 时间转换为小数

[英]SQL Convert & Cast Nvarchar Time to a decimal

I'm working on a legacy db and need to parse info from one db to another, parsing it into the new db is easy enough but first i need to create the query to convert and cast the following in the legacy MSSQL db:我正在处理遗留数据库,需要将信息从一个数据库解析到另一个数据库,将其解析到新数据库很容易,但首先我需要创建查询以在遗留 MSSQL 数据库中转换和转换以下内容:

WorkedHours(NVARCHAR(10)) is in text format 07:30 WorkedHours(NVARCHAR(10))为文本格式 07:30

I need to convert and cast this as a decimal ie 7.5我需要将其转换为小数,即 7.5

I have searched around for the answer to this but can not find anything that has worked, so thought i would put it out there to see if any of you has any ideas我已经四处寻找答案,但找不到任何有效的方法,所以我想我会把它放在那里看看你们是否有任何想法

DATEDIFF(
  MINUTE,
  0,
  CAST('07:30' AS TIME)
)
/
60.0

Works up to '23:59' only仅适用于'23:59'

EDIT:编辑:

Based on a comment elsewhere, you have some 'bad' values.根据其他地方的评论,您有一些“坏”的价值观。

This may find them...这可能会发现他们...

SELECT
  *
FROM
  yourTable
WHERE
  TRY_CONVERT(TIME, worked_hours) IS NULL

And as such, this is a safer version of my expression....因此,这是我表达方式的更安全版本....

DATEDIFF(
  MINUTE,
  0,
  TRY_CONVERT(TIME, worked_hours)
)
/
60.0

(Returns NULL for values that failed to parse.) (对于解析失败的值,返回NULL 。)

This should work in ms-sql and an example-string "1101:56" (1101h & 56 minutes) |这应该适用于 ms-sql 和示例字符串“1101:56”(1101h 和 56 分钟)| in general >24h:一般>24小时:

-- Take all hours before ":" and all Minutes (2 digits) after ":" and convert it to float.
select convert(decimal,left('1101:56',CHARINDEX(':','1101:56')-1))+convert(decimal,right('1101:56',2))/60;

-- with placeholder
select convert(decimal,left(time_str_from_table,CHARINDEX(':',time_str_from_table)-1))+convert(decimal,right(time_str_from_table,2))/60;

If the source table have NULL-Values, than use:如果源表具有 NULL 值,则使用:

-- with placeholder
select isnull( ( convert(decimal,left(time_str_from_table,CHARINDEX(':',time_str_from_table)-1))+convert(decimal,right(time_str_from_table,2))/60 ), 0.0);

There's no reason to pull out the date/time types.没有理由退出日期/时间类型。 Just do some simple string parsing:只需做一些简单的字符串解析:

cast(left(WorkedHours, 2) as int) + cast(right(WorkedHours, 2) as int) / 60.00

This won't have any limitations on 24 hours or anything like that.这对 24 小时或类似的东西没有任何限制。 It just assumes that you've got two digits before a colon and two digits after.它只是假设冒号前有两位数,冒号后有两位数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM