T-SQL 日期时间转换 [英] T-SQL datetime conversion

查看:40
本文介绍了T-SQL 日期时间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用第 3 方数据库,该数据库(无论出于何种原因)内部以 yyyymm 格式存储日期,例如 201212 for Dec 2012 作为 INT.

I'm working with a 3rd party database, which (for whatever reason) internal stores a date in the format yyyymm eg 201212 for Dec 2012 as an INT.

是否有一种简单的方法可以将其转换为 SQL Server DateTime 类型?

Is there a simple way that I may convert this to a SQL Server DateTime type?

我尝试将上述内容手动转换为长度为 6 的字符序列,将其与 '01' 连接以获取给定月份的开始,如下所示:

I've tried manually converting the above to a char seq of length 6, concatenating this with '01' to get the start of a given month like so:

(CONVERT(char(6), Period) + '01')`

然后将其包装在 datetime 转换中:

then wrapping this in a datetime conversion:

CONVERT(datetime, (CONVERT(char(6), Period) + '01'))

但这似乎抛出;

从字符串转换日期和/或时间时转换失败

谁能解释一下我做错了什么?

Can anyone shed any light on what I'm doing wrong?

谢谢!:)

推荐答案

您需要使用正确的参数.这是 msdn 图表 http://msdn.microsoft.com/en-us/library/ms187928.aspx

You need to use the correct parameter. Here's the msdn chart http://msdn.microsoft.com/en-us/library/ms187928.aspx

就您而言,我认为您需要附加01"并使用它

In your case, i believe you need to append the '01' and use this

declare @val VARCHAR(8)

SET @val = '201212'

set @val = @val + '01'

print CONVERT(DATETIME, @val, 12)

12 是 ISO 格式,将采用 yymmdd 或 yyyymmdd

12 is the ISO format and will take either yymmdd or yyyymmdd

这篇关于T-SQL 日期时间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆