views:

139

answers:

4

How can I convert @lastEndTime to a string formated YYYY-MM-DD HH:MM:SS.MS?

DECLARE @lastEndTime datetime
+1  A: 

Really horribly, to get a precise format you have to use the datepart function and build it up.

select datepart(yyyy, @lastEndTime) + '-' + datepart(mm, @lastEndTime) + '-' + datepart(dd, @lastEndTime) +' ' + datepart(hh, @lastEndTime) + ':' + datepart(mm, @lastEndTime) + ':' + datepart(ss, @lastEndTime) + '.' + datepart(ms,@lastEndTime)

You could define it as a function for ease of use though.

Edit - as someone has pointed out, this format happens to be a standard - ODBC canonical so

 CONVERT(CHAR(23), @lastEndTime, 121)

should do it.

Jon Hopkins
yuck that sucks
Kevin
yeah, that does. Fortunately, you don't have to do that for the above ODBC canonical format.
andras
good point @andras - this is 121 I think. I got so used to doing odd formats I always did it manually (which is obviously evil when it comes to performance). Shall update the answer.
Jon Hopkins
+2  A: 

Check the MSDN Books Online documentation for CAST and CONVERT - it has a complete list of all supported, built-in date formats that you can use with CONVERT.

E.g.

 CONVERT(VARCHAR(50), GETDATE(), 100)

will convert today's date and time to a string in the format mon dd yyyy hh:miAM (or PM).

If your string does not match any of those formats, then you either have to

  • use DATEPART function to extract bits and pieces of your DATETIME and concatenate that together manually
  • use SQLCLR and the .NET DateTime function to do it in a SQL-CLR user-defined function
  • don't do it in SQL Server and pass back the DATETIME to the calling client and let the caller handle the conversion to the actual presentation format
marc_s
A: 
CONVERT(nvarchar, @lastEndTime, 121)
andras
A: 

DECLARE @lastEndTime datetime set @lastEndTime = getdate()

select convert(varchar,@lastEndTime,121)

For more style http://msdn.microsoft.com/en-us/library/ms187928.aspx

jfrobishow
@jfrobishow: a one-off error here, I guess. The variant with milliseconds is `121`.
andras