SQL日期函數

1. 當前系統日期、時間
      select getdate()

2. dateadd  在向指定日期加上一段時間的基礎上,返回新的 datetime 值
      例如:向日期加上2天
      select dateadd(day,2,'2004-10-15') --返回:2004-10-17 00:00:00.000

3. datediff 返回跨兩個指定日期的日期和時間邊界數。
      select datediff(day,'2004-09-01','2004-09-18')   --返回:17

4. datepart 返回代表指定日期的指定日期部分的整數。
      select datepart(month, '2004-10-15')  --返回 10

5. datename 返回代表指定日期的指定日期部分的字符串
      select datename(weekday, '2004-10-15')  --返回:星期五

6. day(), month(),year() --可以與datepart對照一下

      select 當前日期=convert(varchar(10),getdate(),120),

             當前時間=convert(varchar(8),getdate(),114)

      select datename(dw,'2004-10-15')

      select 本年第多少周=datename(week,'2004-10-15'),

             今天是周幾=datename(weekday,'2004-10-15')

函數

參數/功能

GetDate( )

返回系統目前的日期與時間

DateDiff (interval,date1,date2)

以interval 指定的方式,返回date2 與date1兩個日期之間的差值 date2-date1

DateAdd (interval,number,date)

以interval指定的方式,加上number之後的日期

DatePart (interval,date)

返回日期date中,interval指定部分所對應的整數值

DateName (interval,date)

返回日期date中,interval指定部分所對應的字符串名稱

參數 interval的設定值如下:

縮 寫(Sql Server) (Access 和 ASP) 說明

Year

Yy yyyy 年 1753 ~ 9999

Quarter

Qq 季 1 ~ 4

Month

Mm 月1 ~ 12

Day of year

Dy y 一年的日數,一年中的第幾日 1-366

Day

Dd 日,1-31

Weekday

Dw w 一週的日數,一週中的第幾日 1-7

Week

Wk ww 周,一年中的第幾周 0 ~ 51

Hour

Hh 時0 ~ 23

Minute

Mi n 分鐘0 ~ 59

Second

Ss s 秒 0 ~ 59

Millisecond

Ms -

毫秒 0 ~ 999

SQL Server中文版的默認的日期字段datetime格式是yyyy-mm-dd Thh:mm:ss.mmm

例如:

select getdate()

2004-09-12 11:06:08.177

整理了一下SQL Server裏面可能經常會用到的日期格式轉換方法:

舉例如下:

select CONVERT(varchar, getdate(), 120 )

2004-09-12 11:06:08

select replace(replace(replace(CONVERT(varchar, getdate(), 120 ),'-',''),' ',''),':','')

20040912110608

select CONVERT(varchar(12) , getdate(), 111 )

2004/09/12

select CONVERT(varchar(12) , getdate(), 112 )

20040912

select CONVERT(varchar(12) , getdate(), 102 )

2004.09.12

select CONVERT(varchar(12) , getdate(), 101 )

09/12/2004

select CONVERT(varchar(12) , getdate(), 103 )

12/09/2004

select CONVERT(varchar(12) , getdate(), 104 )

12.09.2004

select CONVERT(varchar(12) , getdate(), 105 )

12-09-2004

select CONVERT(varchar(12) , getdate(), 106 )

12 09 2004

select CONVERT(varchar(12) , getdate(), 107 )

09 12, 2004

select CONVERT(varchar(12) , getdate(), 108 )

11:06:08

select CONVERT(varchar(12) , getdate(), 109 )

09 12 2004 1

select CONVERT(varchar(12) , getdate(), 110 )

09-12-2004

select CONVERT(varchar(12) , getdate(), 113 )

12 09 2004 1

select CONVERT(varchar(12) , getdate(), 114 )

11:06:08.177

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章