[英]How to get month and year from the date
Using SQL Server 2000 使用SQL Server 2000
Date like 20120101, 20120201, 20120301...
日期20120101, 20120201, 20120301...
Fomat is yyyymmdd
Fomat是yyyymmdd
I want to display month and year from the date like 01/2012, 02/2012, 03/2012... 我想显示01 / 2012、02 / 2012、03 / 2012等日期的月份和年份...
Expected Output 预期产量
01/2012
02/2012
03/2012
I don't want 1/2012, 2/2012, 3/2012...
我不要1 / 1/2012, 2/2012, 3/2012...
Can any one give me a idea or query help.... 任何人都可以给我一个想法或查询帮助...。
You can use something like this: 您可以使用如下形式:
DECLARE @input VARCHAR(20)
SET @input = '20120101'
-- convert the 20120101 to a DATETIME
DECLARE @thedate DATETIME
SELECT @thedate = CONVERT(DATETIME, @input, 112)
-- reformat that DATETIME to your needs
DECLARE @output VARCHAR(20)
SET @output = RIGHT('00' + CAST(DATEPART(MONTH, @thedate) AS VARCHAR(2)), 2) +
'/' + CAST(DATEPART(YEAR, @thedate) AS VARCHAR(4))
SELECT @output
You could "hide" this functionality into a user-defined function to make it more easily usable in your code: 您可以将此功能“隐藏”到用户定义的函数中,以使其更易于在代码中使用:
CREATE FUNCTION dbo.MonthYearFromDate (@input VARCHAR(20))
RETURNS VARCHAR(20)
AS BEGIN
DECLARE @thedate DATETIME
SELECT @thedate = CONVERT(DATETIME, @input, 112)
DECLARE @output VARCHAR(20)
SET @output = RIGHT('00' + CAST(DATEPART(MONTH, @thedate) AS VARCHAR(2)), 2) + '/' + CAST(DATEPART(YEAR, @thedate) AS VARCHAR(4))
RETURN @output
END
and then you can call this like so: 然后可以这样称呼它:
SELECT dbo.MonthYearFromDate('20120515')
and get the output 并获得输出
05/2012
SELECT CAST(datepart(month,getdate()) AS CHAR) + '/' + CAST(datepart(year,getdate()) AS CHAR)
代替函数getdate(),您需要日期字段。
have a look at the SUBSTRING function http://msdn.microsoft.com/en-us/library/ms187748.aspx 看看SUBSTRING函数http://msdn.microsoft.com/en-us/library/ms187748.aspx
You should also consider storing your dates as a DATETIME (I assume you are using VARCHAR?) 您还应该考虑将日期存储为DATETIME(我假设您正在使用VARCHAR?)
Search on extract() function. 搜索extract()函数。 It will solve your problem. 它将解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.