开发者

Formatting Datetime Column

I have a table called FcData and the data looks like:

Op_Date  

2011-02-14 11:53:40.000 
2011-02-17 16:02:19.000 
2010-02-14 12:53:40.000 
2010-02-17 14:02:19.000 

I want the output in the mm/yyyy format sample output should be:

Op_Date

02/2011
02/2011
02/2010
02/2010

I wrote query like :

SELECT CONVERT(VARCHAR开发者_运维知识库,DATEPART(mm,Op_Date
)) + '/' + CONVERT(VARCHAR,DATEPART(yyyy,Op_Date))
 FROM Fcdata

But I am getting output as:

Op_Date

2/2011
2/2011
2/2010
2/2010

Can anyone help me?


I think this is about the shortest code you'll find, and only requires one conversion:

SELECT RIGHT(CONVERT(CHAR(10), Op_Date, 103), 7);

Mapping it to your query:

SELECT Op_Date, RIGHT(CONVERT(CHAR(10), Op_Date, 103), 7)
    FROM dbo.Fcdata;

And the join would be:

SELECT f.*, o.*
    FROM dbo.Fcdata AS f
    INNER JOIN dbo.OtherTable AS o
    ON RIGHT(CONVERT(CHAR(10), f.Op_Date, 103), 7) = o.column_name;

Just don't expect performance to be snappy if the table is large, because the convert is going to force SQL Server to scan every single row.

Also please don't use shorthand like yyyy and mm. Do you know that y and yyyy are different? And that there are now FIVE different shorthands that start with m (m, mi, ms, mm, mcs)? Spell it out. If you mean YEAR, say YEAR. Then it's clear to everyone.


SELECT 
  CASE WHEN LEN(CONVERT(VARCHAR,DATEPART(mm,Op_Date)) = 1 THEN
    '0' + CONVERT(VARCHAR,DATEPART(mm,Op_Date)) + '/' + CONVERT(VARCHAR,DATEPART(yyyy,Op_Date))
  ELSE
    CONVERT(VARCHAR,DATEPART(mm,Op_Date)) + '/' + CONVERT(VARCHAR,DATEPART(yyyy,Op_Date))
  END
FROM Fcdata


SELECT RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(MM, Op_Date)), 2) + '/' + CONVERT(VARCHAR,DATEPART(yyyy,Op_Date))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜