简体   繁体   English

在 SQL Server 查询中返回月份名称

[英]Returning Month Name in SQL Server Query

Using SQL Server 2008 , I have a query that is used to create a view and I'm trying to display a month's name instead of an integer.使用SQL Server 2008 ,我有一个用于创建视图的查询,我试图显示月份的名称而不是整数。

In my database, the datetime is in a column called OrderDateTime .在我的数据库中, datetime时间位于名为OrderDateTime的列中。 The lines in the query that return the date is:查询中返回日期的行是:

DATENAME(yyyy, S0.OrderDateTime) AS OrderYear,
DATEPART(MONTH, S0.OrderDateTime) AS OrderMonth

This returns a column of years and a column of months as integers.这将返回一列年份和一列月份作为整数。 I want to return the month names (Jan, Feb, etc ).我想返回月份名称(Jan, Feb, etc )。 I've tried:我试过了:

CONVERT(varchar(3), DATEPART(MONTH, S0.OrderDateTime) AS OrderMonth

This is obviously is incorrect, as I get这显然是不正确的,因为我得到

Incorrect syntax near 'AS' “AS”附近的语法不正确

message.信息。 What is the proper syntax for my query?我的查询的正确语法是什么?

This will give you the full name of the month.这将为您提供月份的全名。

select datename(month, S0.OrderDateTime)

If you only want the first three letters you can use this如果你只想要前三个字母,你可以使用这个

select convert(char(3), S0.OrderDateTime, 0)

你试过DATENAME(MONTH, S0.OrderDateTime)吗?

Change:改变:

CONVERT(varchar(3), DATEPART(MONTH, S0.OrderDateTime) AS OrderMonth

To:到:

CONVERT(varchar(3), DATENAME(MONTH, S0.OrderDateTime)) AS OrderMonth

尝试这个:

SELECT LEFT(DATENAME(MONTH,Getdate()),3)

从表名中选择SUBSTRING (convert(varchar,S0.OrderDateTime,100),1,3)

在 SQL Server 2012 中,可以使用FORMAT(@mydate, 'MMMM') AS MonthName

这将为您提供您所要求的:

select convert(varchar(3),datename(month, S0.OrderDateTime)) 
SELECT MONTHNAME( `col1` ) FROM `table_name` 
DECLARE @iMonth INT=12
SELECT CHOOSE(@iMonth,'JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER')

Without hitting db we can fetch all months name.无需点击 db 我们就可以获取所有月份的名称。

WITH CTE_Sample1 AS
(
    Select 0 as MonthNumber

    UNION ALL

    select MonthNumber+1 FROM CTE_Sample1
        WHERE MonthNumber+1<12
)

Select DateName( month , DateAdd( month , MonthNumber ,0 ) ) from CTE_Sample1

basically this ...基本上这个...

declare @currentdate datetime = getdate()
select left(datename(month,DATEADD(MONTH, -1, GETDATE())),3)
union all
select left(datename(month,(DATEADD(MONTH, -2, GETDATE()))),3)
union all
select left(datename(month,(DATEADD(MONTH, -3, GETDATE()))),3)

对我来说,由于公司限制,无法访问 DATENAME ......但这也很容易。

FORMAT(date, 'MMMM') AS month

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM