views:

1705

answers:

7

How do I retrieve a date from SQL Server in YYYY-MM-DD format? I need this to work with SQL Server 2000 and up. Is there a simple way to perform this in SQL Server or would it be easier to convert it programatically after I retrieve the result set?

I've read the CAST and CONVERT on Microsoft Technet, but the format I want isn't listed and changing the date format isn't an option.

+2  A: 

The form you are after is listed in the books online documentation.

http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).aspx

For example, try the following:

select convert(varchar,getDate(),120)
select convert(varchar(10),getDate(),120)
John Sansom
why not explicitly mention the length of the varchar and rely on the default?
gbn
Absolutely, ammended accordingly.
John Sansom
If you take the default, in this case, you get the time value - the entire format for format 120 is 'yyyy-mm-dd hh:mi:ss'. By explicitly declaring the length, it is trimmed to the format you specified in yout original note - 'yyyy-mm-dd'.
DaveE
+6  A: 
SELECT CONVERT(char(10), GetDate(),126)

Limiting the size of the varchar chops of the hour portion that you don't want.

Darrel Miller
why not CHAR(10), will it ever change size?
KM
:-) Char sounds good to me! I'll change it.
Darrel Miller
No, but some clients have issues with the fixed length.
gbn
+1  A: 

In your cast and convert link, use style 126 thus:

CONVERT (varchar(10), DTvalue, 126)

This truncates the time. Your requirement to have it in yyyy-mm-dd means it must be a string datatype and datetime.

Frankly though, I'd do it on the client unless you have good reasons not to.

gbn
A: 

SELECT CONVERT(NVARCHAR(20), GETDATE(), 23)

Dmitri Kouminov
why use NVARCHAR(20)? could there be special characters in there?
KM
I prever to use UNICODE. Mos of my projects international ;-)
Dmitri Kouminov
But why NVARCHAR(20)? 40 bytes to store a numeric date? Also, on my system when I run your answer: "SELECT REPLACE(CONVERT(NVARCHAR(20), GETDATE(), 23), '.', '-')", I get the same result without the replace: "CONVERT(NVARCHAR(20), GETDATE(), 23)". Also, conversion style "23" is not defined in my documentation.
KM
You right don't need replace.
Dmitri Kouminov
+1  A: 

I would use:

CONVERT(char(10),GETDATE(),126)
KM
+2  A: 

The convert function with the format specifier 120 will give you the format "yyyy-MM-dd HH:mm:ss", so you just have to limit the length to 10 to get only the date part:

convert(varchar(10), theDate, 120)

However, formatting dates is generally better to do in the presentation layer rather than in the database or business layer.

Example in C#:

theDate.ToString("yyyy-MM-dd")
Guffa
A: 

The BOL description for 126 is a bit confusion (never found an explanation for "T").

nojetlag