datename  day

Chapter 2: Transact-SQL Functions

datepart

Description

Returns the specified datepart in the first argument of the specified date (the second argument) as an integer. Takes a date, time, datetime, or smalldatetime value as its second argument. If the datepart is hour, minute, second, or millisecond, the result is 0.

Syntax

datepart(date_part, date expression)

Parameters

date_part

is a date part. Table 2-7 lists the date parts, the abbreviations recognized by datepart, and the acceptable values.

Table 2-7: Date parts and their values

Date part

Abbreviation

Values

year

yy

1753 – 9999 (2079 for smalldatetime). 0001 to 9999 for date

quarter

qq

1 – 4

month

mm

1 – 12

week

wk

1 – 54

day

dd

1 – 31

dayofyear

dy

1 – 366

weekday

dw

1 – 7 (Sun. – Sat.)

hour

hh

0 – 23

minute

mi

0 – 59

second

ss

0 – 59

millisecond

ms

0 – 999

calweekofyear

cwk

1 – 53

calyearofweek

cyr

1753 – 9999 (2079 for smalldatetime). 0001 to 9999 for date

caldayofweek

cdw

1 – 7

When you enter a year as two digits (yy):

date expression

is an expression of type datetime, smalldatetime, date, time, or a character string in a datetime format.

Examples

Example 1

Assumes a current date of November 25, 1995:

select datepart(month, getdate())
-----------
          11

Example 2

Returns the year of publication from traditional cookbooks:

select datepart(year, pubdate) from titles where type = "trad_cook"
 -----------
        1990 
        1985 
        1987 

Example 3

select datepart(cwk,’1993/01/01’)
-----------
          53

Example 4

select datepart(cyr,’1993/01/01’)
-----------
        1992

Example 5

select datepart(cdw,’1993/01/01’)
-----------
           5

Example 6

Find the hours in a time:

declare @a time
select @a = "20:43:22"
select datepart(hh, @a)
-----------
    20

Example 7

If a hour, minute, or second portion is requested from a date using datename or datepar) the result is the default time, zero. If a month, day, or year is requested from a time using datename or datepart, the result is the default date, Jan 1 1900:

--Find the hours in a date
declare @a date
select @a = "apr 12, 0001"
select datepart(hh, @a)
-----------
    0
--Find the month of a time
declare @a time
select @a = "20:43:22"
select datename(mm, @a)
------------------------------
January

When you give a null value to a datetime function as a parameter, NULL is returned.

Usage

Standards

ANSI SQL – Compliance level: Transact-SQL extension.

Permissions

Any user can execute datepart.

See also

Datatypes Date and time datatypes

Commands select, where clause

Functions dateadd, datediff, datename, getdate





Copyright © 2005. Sybase Inc. All rights reserved. day

View this book as PDF