views:

203

answers:

5

Hi i need to wirte sql query in such a way that it will retrive the date in the following format dd MM yyyy HH mm ss AM(or PM)

eg 31 12 2009 12 45 06 AN

A: 

Use DATE_FORMAT function. Here is the reference for formats: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format

Deniss Kozlovs
hi Iam using sqlserver 2005
+2  A: 

You could take a look at CAST and CONVERT on MSDN.

SELECT CONVERT(VARCHAR(30), datetime_field, 130) AS formatted_date

The 130 will convert the date to the following format: dd mon yyyy hh:mi:ss:mmmAM (or PM)

Zaagmans
HI this format is not available on the listdd MM yyyy HH mm ss AM(or PM)
I think converting to datetime style 130 comes closest to your requested date
Zaagmans
+1  A: 

It would be hard to get it more inefficient as this but here goes

DECLARE @GetDate DATETIME
SET @GetDate = '01-01-2009 13:10:20'
SELECT 
  CAST(DATEPART(dd, @GETDATE) AS VARCHAR(2)) + ' '
  + CAST(DATEPART(mm, @GETDATE) AS VARCHAR(2)) + ' '
  + CAST(DATEPART(yyyy, @GETDATE) AS VARCHAR(4)) + ' '
  + CAST(DATEPART(hh, @GETDATE)%12 AS VARCHAR(2)) + ' '
  + CAST(DATEPART(mi, @GETDATE) AS VARCHAR(2)) + ' '
  + CAST(DATEPART(ss, @GETDATE) AS VARCHAR(2)) + ' '
  + CASE WHEN DATEPART(hh, @GETDATE) > 12 THEN 'AM' ELSE 'PM' END
Lieven
Shouldn't it be : CASE WHEN DATEPART (hh,@GETDATE) < 12 THEN 'AM'?
Zaagmans
@Zaagmans - honestly, I have no idea. AM/PM is one of those things I can't get to stick into my mind. If AM is after midday, you're right. If PM is past midday, you're wrong <g>
Lieven
+1 for the effort!
Learning
A: 

If you're using SQL 2005 and 2008 a good way to go is to write a CLR procedure to do the formatting for you. The .NET framework has very powerful formatting routines for various data types and it makes sense to exploit them when you want to do formatting at a database level.

Although whether this should be the case if of course highly debatable. I can understand the SQL Server team's rationale in not bending over backwards to support flexible formatting given that a database's main job is to store and retrieve data.

Conrad
+3  A: 

I would recommend formatting the string on the middle layer/tier or the client side. It's so much easier with various format methods... This is a presentation requirement, why don't you format in in the presentation layer, then?

Pawel Krakowiak
+1 No idea why this should have been downgraded. It's solid advice.
Lieven