如何在SQL Server中以YY格式获取年份

时间:2013-08-09 07:09:17

标签: sql sql-server datetime

select Year(Creation_Date) 
from Asset_Creation 
where Creation_Date = @Creation_Date

我正在执行此查询,我今天提供2013年份。我希望查询只返回2013年的13个。我怎样才能实现呢?

7 个答案:

答案 0 :(得分:17)

尝试

SELECT RIGHT(YEAR(Creation_Date), 2) YY 
  FROM Asset_Creation 
 WHERE ...

示例输出:

| YY |
------
| 10 |
| 11 |
| 13 |

这是 SQLFiddle 演示

答案 1 :(得分:6)

对于SQL Server 2012:

SELECT FORMAT(@Creation_Date, 'yy')

答案 2 :(得分:2)

鉴于您只使用两位数存储了2100年的问题,我假设您只需要在2000年到2099年间工作的代码。在这种情况下,只需减去2000:

select Year(Creation_Date) - 2000
from Asset_Creation 
where Creation_Date = @Creation_Date

答案 3 :(得分:1)

select SUBSTRING(Year(Creation_Date), 2, 2)
from Asset_Creation 
where Creation_Date = @Creation_Date

答案 4 :(得分:1)

怎么样;

SUBSTRING(YEAR(Creation_Date), 3, 2)

答案 5 :(得分:1)

你可以在这里使用一个非常有用的功能

像这样称呼它

SELECT dbo.fnFormatDate (getdate(), ‘MM/DD/YY’) 

功能

CREATE FUNCTION dbo.fnFormatDate (@Datetime DATETIME, @FormatMask VARCHAR(32))
RETURNS VARCHAR(32)
AS
BEGIN
    DECLARE @StringDate VARCHAR(32)
    SET @StringDate = @FormatMask
    IF (CHARINDEX (‘YYYY’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘YYYY’,
                         DATENAME(YY, @Datetime))
    IF (CHARINDEX (‘YY’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘YY’,
                         RIGHT(DATENAME(YY, @Datetime),2))
    IF (CHARINDEX (‘Month’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘Month’,
                         DATENAME(MM, @Datetime))
    IF (CHARINDEX (‘MON’,@StringDate COLLATE SQL_Latin1_General_CP1_CS_AS)>0)
       SET @StringDate = REPLACE(@StringDate, ‘MON’,
                         LEFT(UPPER(DATENAME(MM, @Datetime)),3))
    IF (CHARINDEX (‘Mon’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘Mon’,
                                     LEFT(DATENAME(MM, @Datetime),3))
    IF (CHARINDEX (‘MM’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘MM’,
                  RIGHT(’0′+CONVERT(VARCHAR,DATEPART(MM, @Datetime)),2))
    IF (CHARINDEX (‘M’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘M’,
                         CONVERT(VARCHAR,DATEPART(MM, @Datetime)))
    IF (CHARINDEX (‘DD’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘DD’,
                         RIGHT(’0′+DATENAME(DD, @Datetime),2))
    IF (CHARINDEX (‘D’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘D’,
                                     DATENAME(DD, @Datetime))   
RETURN @StringDate
END
GO

答案 6 :(得分:0)

实际上在SQLServer中你可以使用Convert函数的format参数设置为1语法将是Convert(varchar(10),@ YourDate,1)