Difference between revisions of "DATEPART"

From SQLZOO
Jump to: navigation, search
(Created page with "<table align='right' border='1'> <caption>Compatibility</caption> <tr><th colspan='3'>DATEPART(YEAR, d)</th></tr> <tr><td align='center'>'''Engine'''</td><td align='center'>''...")
 
Line 12: Line 12:
 
<p>DATEPART allows you to retrieve components of a date.</p>
 
<p>DATEPART allows you to retrieve components of a date.</p>
 
<p>You can extract also YEAR, MONTH, DAY, HOUR, MINUTE, SECOND.</p>  
 
<p>You can extract also YEAR, MONTH, DAY, HOUR, MINUTE, SECOND.</p>  
<pre style='width:50ex'>
+
<pre style='width:70ex'>
 
   DATEPART(YEAR, d)    DATEPART(MONTH, d)
 
   DATEPART(YEAR, d)    DATEPART(MONTH, d)
 
   DATEPART(DAY, d)    DATEPART(HOUR, d)
 
   DATEPART(DAY, d)    DATEPART(HOUR, d)
Line 20: Line 20:
 
<div class='ht'>
 
<div class='ht'>
 
In this example you get the year and the month from the date <code>whn</code>.
 
In this example you get the year and the month from the date <code>whn</code>.
<source lang='sql' class='def e-sqlserver>
+
<source lang='sql' class='def e-sqlserver'>
 
SELECT whn
 
SELECT whn
 
       ,DATEPART(YEAR, whn)  AS yr
 
       ,DATEPART(YEAR, whn)  AS yr

Revision as of 11:04, 13 July 2012

Compatibility
DATEPART(YEAR, d)
EngineOKAlternative
ingresNoEXTRACT(YEAR FROM d)
mysqlNoEXTRACT(YEAR FROM d)
oracleNoEXTRACT(YEAR FROM d)
postgresNoEXTRACT(YEAR FROM d)
sqlserverYes

DATEPART

DATEPART allows you to retrieve components of a date.

You can extract also YEAR, MONTH, DAY, HOUR, MINUTE, SECOND.

   DATEPART(YEAR, d)    DATEPART(MONTH, d)
   DATEPART(DAY, d)     DATEPART(HOUR, d)
   DATEPART(MINUTE, d)  DATEPART(SECOND, d) 

In this example you get the year and the month from the date whn.

SELECT whn
      ,DATEPART(YEAR, whn)  AS yr
      ,DATEPART(MONTH, whn) AS mnth
  FROM eclipse
SELECT whn
      ,EXTRACT(YEAR FROM td)  AS yr
      ,EXTRACT(MONTH FROM td) AS hr
  FROM eclipse

See also

Personal tools
Namespaces

Variants
Actions
Reference
Toolbox
Google AdSense