【问题标题】:Get only month and year in SQL Server在 SQL Server 中仅获取月份和年份
【发布时间】:2019-03-02 14:08:00
【问题描述】:

我只想从 SQL Server 中的日期列中获取月份和年份。

例如:如果今天的日期是02/03/2019,那么我想要0319

注意:我希望结果的顺序相同(2 位数月份和 2 位数年份)。不应从月份中删除零。

【问题讨论】:

    标签: sql sql-server sql-server-2008


    【解决方案1】:

    作为替代方法,您可以选择:

    RIGHT(REPLACE(CONVERT(varchar(8),DateColumn,3),'/',''),4)
    

    【讨论】:

      【解决方案2】:

      您可以使用以下方法创建号码:

      select month(datecol) * 100 + (year(datecol) % 100)
      

      添加零需要更多的工作:

      select right('0' + convert(varchar(255), month(datecol) * 100 + (year(datecol) % 100)), 4)
      

      或者,您可以使用format()

      select format(datecol, 'MMyy')
      

      【讨论】:

        【解决方案3】:

        你可以试试这个

        substring(convert(nvarchar,@date,12),3,2) + left(convert(nvarchar,@date,12),2)
        

        您可以创建一个用户定义的函数,然后应用到您的列/s

        create function udf_Getmonthyear(@date as date)
        RETURNS nchar(4)
        BEGIN
            DECLARE @d_format nchar(6) = (select convert(nvarchar,@date,12))
        
            RETURN (select SUBSTRING(@d_format,3,2) + left(@d_format,2)) 
        end
        go
        

        【讨论】:

          【解决方案4】:

          在 TSQL 中使用函数 DATEPART 获取 DateTime 值的任何部分。例如:

          DATEPART(yy,datecol) 为您提供 DateTime 列的 4 位数年份部分(例如:datecol),使用 %(模数)运算符可以获得 2 位数年份 DATEPART(yy,datecol)%100DATEPART(mm,datecol) 为您提供 datecol 字段的月份部分。

          select Right('0'+cast(DATEPART(mm,datecol) as varchar(2)),2) +
                 Right('0'+cast(DATEPART(yy,datecol)%100 as varchar(2)),2) MonthYearPart
          from MyTable
          

          问候

          【讨论】:

            猜你喜欢
            • 2010-12-19
            • 1970-01-01
            • 1970-01-01
            • 2010-09-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-04-28
            相关资源
            最近更新 更多