select Year(Creation_Date)
from Asset_Creation
where Creation_Date = @Creation_Date
我正在执行这个查询,我得到的是2013
今天提供的年份。我希望查询仅返回 2013 年的 13 个。我怎样才能做到这一点?
select Year(Creation_Date)
from Asset_Creation
where Creation_Date = @Creation_Date
我正在执行这个查询,我得到的是2013
今天提供的年份。我希望查询仅返回 2013 年的 13 个。我怎样才能做到这一点?
尝试
SELECT RIGHT(YEAR(Creation_Date), 2) YY
FROM Asset_Creation
WHERE ...
样本输出:
| YY | ------ | 10 | | 11 | | 13 |
这是SQLFiddle演示
对于 SQL Server 2012:
SELECT FORMAT(@Creation_Date, 'yy')
假设您只使用两位数来存储 2100 年的问题,那么我假设您只需要在 2000 和 2099 之间工作的代码。在这种情况下,只需减去 2000:
select Year(Creation_Date) - 2000
from Asset_Creation
where Creation_Date = @Creation_Date
select SUBSTRING(Year(Creation_Date), 2, 2)
from Asset_Creation
where Creation_Date = @Creation_Date
怎么样;
SUBSTRING(YEAR(Creation_Date), 3, 2)
您可以在这里使用一个非常有用的功能
像这样称呼它
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
实际上,在 SQLServer 中,您可以使用将 Convert 函数的格式参数设置为 1 语法将是 Convert(varchar(10), @YourDate, 1)