【问题标题】:T-SQL Date Format with Substring带有子字符串的 T-SQL 日期格式
【发布时间】:2011-12-21 14:40:25
【问题描述】:

我们有一个名为 target_date 的字段。这是一个字符串。我们需要从该字段中提取月份和年份。

示例: 2011 年 1 月 10 日(日/月/年) 我们正在尝试

 substring(target date,findstring(targetdate,"/",1)+1,(findstring(targetdate,"/",2)-findstring(targetdate,"/",1)+1)).

请帮帮我。

谢谢。

【问题讨论】:

    标签: sql-server tsql substring


    【解决方案1】:

    好吧,这里的第一个问题是您将日期时间存储为字符串。我会假设无论出于何种原因你都无法解决这个问题......

    在这种情况下我会做的是使用convert()函数

    convert(datetime, target_date, 103)
    

    然后使用month()year() 提取所需的值

    【讨论】:

      【解决方案2】:

      说明

      1. 使用CAST and CONVERT (Transact-SQL) 将您的字符串转换为日期时间。
      2. 使用DATEPART (Transact-SQL) 提取月份和年份。

      样本

          -- this will give you the month of your target_date
          datePart(mm, convert(datetime, target_date, 103)) 
      
          -- this will give you the year of your target_date
          datePart(yyyy, convert(datetime, target_date, 103)) -- 2011
          -- or
          datePart(yy, convert(datetime, target_date, 103)) -- 11
      

      【讨论】:

        【解决方案3】:
        declare @date varchar(10)
        
        set @date = '1/10/2011'
        
        select DATEPART(yyyy, CONVERT(datetime, @date, 103)), DATEPART(mm, CONVERT(datetime, @date, 103))
        

        【讨论】:

          【解决方案4】:

          试试这个:

          Month : left(right(target_date , 7),2)
          Year: right(target_date , 4)
          

          如果 target_date 的格式始终相同(即 dd/mm/yyyy)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-10-15
            • 1970-01-01
            • 1970-01-01
            • 2018-03-11
            • 2013-08-17
            • 1970-01-01
            • 2014-12-04
            • 1970-01-01
            相关资源
            最近更新 更多