【问题标题】:SQL convert month and year to date formatSQL将月份和年份转换为日期格式
【发布时间】:2021-04-09 00:43:36
【问题描述】:

我想将服务月列转换为服务日期列。

例如,如果 monthofservice 列有 199012,那么我希望 servicedate 列以 1990-12-01 year-mm-date 格式显示/加载数据。我希望日期始终默认为 01。当monthofservice 列为NULL 时,我还希望servicedate 列显示NULL。使用下面的代码,当monthofservice 为NULL 时,它显示为'-'。

我确信有更好的方法来编写代码,并且当服务月列为 NULL 时也将 servicedate 显示为 NULL。非常感谢任何帮助!

SELECT monthofservice 

,CASE WHEN monthofservice = '' THEN NULL ELSE CAST (concat(substring(monthofservice,1,4),+ '-', substring (MonthofService,5,2)+'-'+ '01')) AS VARCHAR (10)) AS servicedate

FROM transaction  

注意:事务表中不存在 Servicedate 列,因此我使用 trasaction 中的 monthofservice 列转换为 servicedate,然后使用 SSIS 包将数据加载到其他目标表中。如果我可以通过 select 语句提取 NULL,那么我认为其他进程应该完成这项工作。

谢谢!

【问题讨论】:

  • monthofservice的数据类型是什么?
  • 感谢您的回复 Monthofservice 是字符串。从 char 字符串转换日期和/或时间时出现错误转换失败。另外,我希望它在 MonthofService 为 NULL 时将 servicedate 显示为 NULL

标签: sql sql-server function tsql datetime


【解决方案1】:

如果服务月份是一个字符串,你可以这样做:

select convert(date, concat(monthofservice, '01'))

如果 monthofservice 的值不正确,请改用 try_convert()

哦,如果monthofservice 是整数,那也可以。 Here 是一个 dbfiddle。

如果年份和月份在不同的列中,我会推荐datefromparts()

select datefromparts(yyyy, mm, 1)

【讨论】:

  • 感谢您的回复 Monthofservice 是字符串。从 char 字符串转换日期和/或时间时出现错误转换失败。另外,我希望它在 MonthofService 为 NULL 时将 servicedate 显示为 NULL
  • @codelearner 。 . .这表明您在该列中有一些无效值。
  • 我的意思是它工作得很好。非常感谢!我发布了另一个问题,我需要关于不同代码的帮助。
  • 嗨@Gordon Linoff 我现在想从服务月份获取数据,它是字符 (YYYYMM) 格式,所以它有 202012 所以想只提取 3 到 6 个字符,这意味着我想要servicedatetext 为 2012 (YYMM) 格式,因此它需要一些调整,因为当服务月为 NULL 时它显示为空白。我希望在服务月为 NULL 时有 NULL。我使用 CAST(CONCAT(substring(MonthofService,3,2),substring(MonthofService,5,2)) as Varchar (4)) 作为 servicedatetext Servicedatetext 是 varchar 而monthofservice 是 char。
  • @codelearner 。 . .或许您应该提出一个新的问题,详细说明您想要什么,并提供样本数据和想要的结果。
猜你喜欢
  • 1970-01-01
  • 2021-07-04
  • 2018-12-24
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多