Skip to Content
SQL Pocket Guide, 3rd Edition
book

SQL Pocket Guide, 3rd Edition

by Jonathan Gennick
November 2010
Intermediate to advanced
204 pages
4h 23m
English
O'Reilly Media, Inc.
Content preview from SQL Pocket Guide, 3rd Edition

Datetime Conversions: SQL Server

In SQL Server, you can choose one of four overall approaches to datetime conversion. The CONVERT function is a good general choice, although DATENAME and DATEPART provide a great deal of flexibility when converting to text.

CAST and SET DATEFORMAT

SQL Server supports the standard CAST function and also allows you to specify a datetime format using the SET DATEFORMAT command:

SET DATEFORMAT dmy
SELECT CAST('1/12/2004' AS datetime)

2004-12-01 00:00:00.000

For dates in unambiguous formats, you may not need to worry about the DATEFORMAT setting:

SET DATEFORMAT dmy
SELECT CAST('12-Jan-2004' AS datetime)

2004-01-12 00:00:00.000

When using SET DATEFORMAT, you can specify any of the following arguments: mdy, dmy, ymd, myd, dym.

CONVERT

You can use the CONVERT function for general datetime conversions:

CONVERT(datatype[(length)], expression[, style])

The optional style argument allows you to specify the target and source formats for datetime values, depending on whether you are converting to or from a character string. Table 1-4 lists the supported styles.

For example, you can convert to and from text:

SELECT CONVERT(VARCHAR,
          CONVERT(DATETIME, '15-Nov-1961', 106),
          106)

15 Nov 1961

Use the length argument if you want to specify the length of the resulting character string type. Subtract 100 from most style numbers for two-digit years:

SELECT CONVERT(DATETIME, '1/1/50', 1)

1950-01-01 00:00:00.000

SELECT CONVERT(DATETIME, '49.1.1', 2)

2049-01-01 00:00:00.000

SQL Server uses ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

You might also like

SQL Pocket Guide, 2nd Edition

SQL Pocket Guide, 2nd Edition

Jonathan Gennick
SQL Cookbook, 2nd Edition

SQL Cookbook, 2nd Edition

Anthony Molinaro, Robert de Graaf
SQL in a Nutshell, 4th Edition

SQL in a Nutshell, 4th Edition

Kevin Kline, Regina O. Obe, Leo S. Hsu

Publisher Resources

ISBN: 9781449397586Errata Page