【问题标题】:string to date conversion issue SQL字符串到日期转换问题 SQL
【发布时间】:2016-12-29 03:38:22
【问题描述】:

我在以下转换中遇到问题: 我正在使用两个主表客户端和 cli-identifier(这包含信息列)

我在 cli-identifier 表中有一个名为 information 当前以两种方式保存日期的列(唯一改变的是日期值):

First: 22/11/16 * Company info A/C
Second: 22/11/2016 * Company info A/C

我使用以下查询从列中切出信息:

 left(Substring(ci.information, charindex('[0-9]',ci.information),103)
     ,charindex('*',ci.information + '*')-2) as datereceived

之后我收到以下字符串: example of the two different types showing

22/11/16
22/11/2016

我需要这些转换后的日期/时间或只是日期,但无法使用以下代码执行此操作(我也尝试过使用 cast 来执行此操作):

convert(date,left(Substring(ci.information, charindex('[0-9]',ci.information),103),
 charindex('*',ci.information + '*')-2),1) as datereceived

我尝试过的其他方法是将其转换为临时表,然后使用以下方法转换日期。

select 
 cast (t AS date()
 from #a

我知道冲突在于日期值被格式化为 22/11/16 任何输入都会有所帮助。我想到的唯一解决方案是添加到临时表并进行查询以在 22/11/16 年的前面插入“20”值。

【问题讨论】:

  • 是sql还是mysql?
  • 对不起,只是 sql 添加了错误的标签。

标签: sql-server codeigniter date


【解决方案1】:

如果您使用SQL Server,您可以这样做,只需检测日期字符串的长度并使用样式 3 或 103

select  CONVERT( DATETIME , '22/11/16', 3),
        CONVERT( DATETIME , '22/11/2016', 103)

【讨论】:

    【解决方案2】:

    好的,谢谢。 我添加了以下内容来计算字符串的长度。

    case when len(left(Substring(ci.information, charindex('[0-9]',ci.information),103),charindex('*',ci.information + '*')-2)) >= 10
    
     then convert(date,left(Substring(ci.information, charindex('[0-9]',ci.information),103),charindex('*',ci.information + '*')-2),103)
    
     else convert(date,left(Substring(ci.information, charindex('[0-9]',ci.information),103),charindex('*',ci.information + '*')-2),3)
     end as datereceived
    

    问候,

    【讨论】:

      猜你喜欢
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 2010-10-19
      • 2013-04-14
      相关资源
      最近更新 更多