首页 > 解决方案 > 将 YYYYMM 字符串转换为第 1 天的日期 YYYY-MM-DD

问题描述

我从表格中有这个列Startmonth,它是这样的日期:YYYYMM,所以201801201707等。

我希望在我的视图中创建此列,但将其转换为日期,例如YYYY-MM-DD,其中日期为每月的第一天,因此 **201801 > 2018-01-01 和 201707 > 2017- 07-01。**

我不断收到错误:

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

有人可以帮我吗?

我试过这个:

select convert (DATE, concat (s.StartMonth,'01'), 102) as SubscriptionStart

from incident i

left join imcustomerid cid on i.accountid = cid.accountid
left join billing_subscription s on cid.imcustomerid = s.idcustomer
left join billing_subscriptiontype st on s.idsubscriptiontype = st.id

标签: sqlsql-server

解决方案


尝试使用

select convert (DATE, concat (s.StartMonth,'01'), 112) as SubscriptionStart

或者

select cast(concat (s.StartMonth,'01') as date) as SubscriptionStart

转换和转换 (Transact-SQL)

TRY_CONVERT正如@Larnu 所说,我认为在这里使用更好:

select try_convert(date, s.StartMonth+'01', 112) as SubscriptionStart

+不是CONCAT正确转换 NULL 值。


推荐阅读