SQL 将 int 转换为时间
我有一个将时间显示为整数的数据库。但是我想将其输出到具有正确格式的报告中。这是我想更改的格式:
例如。
183000
将变为18:30
500
将变为00:05
160000
将变为16:00
等等。
我已经查看并进行了 CAST 和 CONVERT,但没有成功地以正确的格式获取该时间。
I have a database that displays time as an integer. However I am wanting to output this into a report with the correct format. This is the format that I would like to change:
eg.
183000
would become18:30
500
would become00:05
160000
would become16:00
and so on.
I have had a look and CAST and CONVERT but not successfully managed to get this the time in the correct format.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
假设您的输入始终是 int,您可以使用以下内容解析它:
我绝对希望将此字段更改为实际时间或日期时间字段,因为不建议进行这种级别的转换,特别是对于频繁使用的数据库。确实需要有一种更好的方法来存储数据。
以这种方式使用 int 值会产生大量错误数据,而无需对输入添加大量额外的检查和/或约束(即:260000、127900 等)
Assuming your input will always be an int, you can parse it with something like:
I'd DEFINITELY look to change this field to an actual time or datetime field, as this level of conversion is not advised, especially for a heavily used database. There's just really got to be a better way to store your data.
Using an int value this way allows for a lot of bad data, without adding a lot of additional checks and/or constraints on your inputs (i.e.: 260000, 127900, etc.)
看起来您需要除以 100 来获取秒,除以 10000 来获取分钟,除以 1000000 来获取小时,然后将这些值格式化为字符串,在小时和分钟之间插入冒号,例如
looks like you need to divide by 100 to get the seconds, divide by 10000 to get the minutes, and divide by 1000000 to get the hours, then format those values as a string, inserting a colon between hours and minutes, like
首先转换为 varchar 字段,并将所有时间转换为 4 位数字,如果需要的话添加前导零(500 将变为 0500),然后使用串联 Left(myfield,2) + ':' + right(myfield,2) 分解该字段
每次运行报表时都这样做很愚蠢,会浪费服务器资源。如果可能,将该字段更改为 varchar 并运行代码一次。如果不可能,您可以添加一个格式化字段并让触发器在插入时进行格式化(您仍然需要第一次更新该字段吗?可能可以使用约束而不是触发器,但这取决于数据库。
First cast to a varchar field and convert all times to 4 digits adding leading zeros if need be (500 would become 0500)and then break up the field with concantenation Left(myfield,2) + ':' + right(myfield,2)
This is something stupid to do every time you run a report, it is wasteful of server resources. If possible change the field to varchar and runthe code once. If not possible, can you add a formatted field and have a trigger do the formatiing on insertion (you'll still need to update the field the first time? Possibly a constraint would do instead of a trigger, but that would depend on the database.
根据
CONVERT
的使用以及您之前的问题,我假设您使用的是 SQL Server。您也可以使用
DATEADD
来实现此目的。I'm assuming that you are on SQL Server based on use of
CONVERT
and your previous questions.You could use
DATEADD
for this too.