仅获取 SQL 服务器中的月份和年份
Get only month and year in SQL Server
我只想从 SQL 服务器的日期列中获取月份和年份。
示例:如果今天的日期是02/03/2019
,那么我想要0319
。
注意:我想要相同顺序的结果(2 位数月份和 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')
作为替代方法,您可以选择:
RIGHT(REPLACE(CONVERT(varchar(8),DateColumn,3),'/',''),4)
你可以试试这个
substring(convert(nvarchar,@date,12),3,2) + left(convert(nvarchar,@date,12),2)
您可以创建一个用户定义的函数,然后应用到您的column/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
在 TSQL 中使用函数 DATEPART
获取 DateTime
值的任何部分。例如:
DATEPART(yy,datecol)
为您提供 DateTime
列的 4 位数年份部分(例如:datecol
),使用 %
(模数)运算符您可以获得 2 位数年 DATEPART(yy,datecol)%100
。
DATEPART(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
此致
我只想从 SQL 服务器的日期列中获取月份和年份。
示例:如果今天的日期是02/03/2019
,那么我想要0319
。
注意:我想要相同顺序的结果(2 位数月份和 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')
作为替代方法,您可以选择:
RIGHT(REPLACE(CONVERT(varchar(8),DateColumn,3),'/',''),4)
你可以试试这个
substring(convert(nvarchar,@date,12),3,2) + left(convert(nvarchar,@date,12),2)
您可以创建一个用户定义的函数,然后应用到您的column/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
在 TSQL 中使用函数 DATEPART
获取 DateTime
值的任何部分。例如:
DATEPART(yy,datecol)
为您提供 DateTime
列的 4 位数年份部分(例如:datecol
),使用 %
(模数)运算符您可以获得 2 位数年 DATEPART(yy,datecol)%100
。
DATEPART(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
此致