SQL常用日期處理函數

來源:互聯網
上載者:User

最近在在一電力系統,裡面用到報表,經常需要對SQL日期進行操作。現在將一些常用的SQL日期操作函數記下

/**//**//**//* datepart()函數的使用                          
* datepart()函數可以方便的取到時期中的各個部分
*如日期:2006-07--02 18:15:36.513
* yy:取年           2006
* mm:取月           7
* dd:取月中的天     2
* dy:取年中的天     183
* wk:取年中的周     27
* dw:取周中的天     1
* qq:取年中的季度   3
* hh:取小時        18
* mi:取分鐘        15
* ss:取秒          36
* 以下簡單的語句可以示範所取到的結果
*/
select getdate()
select datepart(mm,getdate())
select datepart(yy,getDate())
select datepart(dd,getdate())
select datepart(dy,getdate())
select datepart(wk,getdate())
select datepart(dw,getdate())
select datepart(qq,getdate())
select datepart(hh,getdate())
select datepart(mi,getdate())
select datepart(ss,getdate())

select datediff(dd,getdate(),'12/25/2006')--計算從今天到12/25/2006還有多少天
select datediff(mm,getdate(),'12/25/2006')--計算從今天到12/25/2006還有多少個月
select datename(mm,getdate())             --以字串而不是數位形式得到今天的月份(07)
 
select dateadd(dd,30,getdate())           --在目前的日期日期上加30天
select dateadd(mm,3,getdate())            --在目前的日期日期上加3個月
select dateadd(yy,1,getdate())            --在目前的日期日期上加1年

select DATEADD(qq,DATEDIFF(qq,0,getdate()), 0)--得到本季度第一天
select dateadd(mm,-3,DATEADD(qq,  DATEDIFF(qq,0,getdate()),  0)) --得到上主、季度第一天--另外使用getdate()函數返回的日期包括到毫秒級,有時我們只需要取出一部分如 2007-05-26 
select convert(varchar(10),getdate(),120)--結果2007-05-26 
/**//*
說明 varchar(10)為截取長度為10個字元
getdate()是需要處理的日期,也可以直接給日期文字
如:2007-05-26 10:00:28.420
120:為getdate()的格式具體可參看以下列表
 參數 結果  
 100  05  8 2006  9:27PM 
 101  05/08/2006 
 102  2006.05.08 
 103  08/05/2006 
 104  08.05.2006 
 105  08-05-2006 
 106  08 05 2006 
 107  05 08, 2006 
 108  21:30:51 
 109  05  8 2006  9:31:11 
 110  05-08-2006 
 111  2006/05/08 
 112  20060508 
 113  08 05 2006 21:31:59 
 114  21:33:06:503 
 120  2006-05-08 21:33:38 

*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.