Home > Database > Mysql Tutorial > body text

SQL Server时间函数用法详解

WBOY
Release: 2016-06-07 16:18:09
Original
1001 people have browsed it

SQL中的时间函数非常有用,特别是在我们进行初始赋值、复杂查询的时候,就显得特别方便。 1、获得系统当前时间 select getdate() 2、DateName (datepart , date )返回表示指定日期的指定日期部分的字符串。 --今天是2009-2-24--星期二 SELECT DATENAME(year,

  SQL中的时间函数非常有用,特别是在我们进行初始赋值、复杂查询的时候,,就显得特别方便。

  1、获得系统当前时间

  select getdate()

  2、DateName (datepart , date )返回表示指定日期的指定日期部分的字符串。

  --今天是2009-2-24--星期二

  SELECT DATENAME(year, getdate()) AS 'Year Name' --------返回:2009

  SELECT DATENAME(month, getdate()) AS 'Month Name' --------返回:02

  SELECT DATENAME(weekday, getdate()) AS 'Weekday Name'------返回:星期二

  3、DATEADD (datepart , number, date),在向指定日期加上一段时间的基础上,返回新的 datetime 值。

  select DateAdd(MM,2,'2008-8-8') --------------返回:2008-10-08 00:00:00.000

  select DateAdd(dd,2,'2008-8-8') --------------返回:2008-08-10 00:00:00.000

  select dateadd(hh,-1,getdate()) --------------返回:2009-02-23 12:46:46.450,返回前一个小时的时间

  4、DATEDIFF ( date-part, date-expression-1, date-expression-2 ) 返回两个日期之间的间隔。

  此函数计算两个指定日期之间日期部分的数目。结果为日期部分中等于(date2 - date1)的有符号的整数值。

  SELECT datediff( hour, '4:00AM', '5:50AM' )---------------------------返回: 1

  SELECT datediff( month, '1987/05/02', '1995/11/15' )------------------返回: 102

  SELECT datediff( day, '00:00', '23:59' )------------------------------返回:0

  SELECT datediff( day, '1999/07/19 00:00', '1999/07/23 23:59' )------返回:4

  SELECT datediff( month, '1999/07/19', '1999/07/23' )------------------返回:0

  SELECT datediff( month, '1999/07/19', '1999/08/23' )------------------返回:1

  实例:查询当天更新的数据

  select * from tableName where datediff(dd,F_EditTime,getdate())=0

  5、DATEPART (datepart,date)返回代表指定日期的指定日期部分的整数。

  --今天是2009-2-24 星期二

  SELECT DATEPART(year,getdate()) as 'Year' --------返回:2009

  SELECT DATEPART(month,getdate()) as 'Month' ---------返回:2

  SELECT DATEPART(weekday,getdate()) as 'Weekday' ---------返回:3,如:Sunday = 1、Saturday = 7

  SELECT DAY(getdate()) -----------------------返回:24

  备注:DAY、MONTH、和 YEAR 函数分别是 DATEPART(dd, date)、DATEPART(mm, date)、和 DATEPART(yy, date) 的同义词。

  附录:datepart

SQL Server时间函数用法详解

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!