T SQL常用日期函式

2021-09-08 08:50:52 字數 3488 閱讀 1534

/*

environment: win7 + sql server 2008 r2

author: cc

desctiption:

常用日期函式整理:

day,month,year , datepart

dateadd,datename ,

datediff ,isdate 的使用

*/--

擷取乙個時間的年,月,日

select

day(getdate

()) ,

month(getdate()) --

month() 函式的引數為整數時,一律返回整數值1,即sql server 認為其是1900 年1 月。

,year(getdate()) --

其日期值應在2023年到2023年之間,這是sql server系統所能識別的日期範圍,否則會出現錯誤。

--運用datepart函式

union

allselect

datepart(day , getdate

()) ,

datepart(month , getdate

()) ,

datepart(year , getdate

())/*

(無列名) (無列名) (無列名)

17 7 2012

17 7 2012

*/select

datename (dd,getdate()) --

返回型別為字元型

/*(無列名)

17

*/--

用 dateadd 來獲得下乙個時間或之前的時間日期

select

dateadd (dd , 1 , getdate()) --

當前時間的下一天

, dateadd (mm , 1 , getdate()) --

當前時間的下乙個月

, dateadd (yy , 1 , getdate()) --

當前時間的下一年

, dateadd (dd , -

1 , getdate()) --

當前時間的前一天

, dateadd (mm , -

1 , getdate()) --

當前時間的前乙個月

, dateadd (yy , -

1 , getdate()) --

當前時間的前一年

--2012-07-18 15:47:05.663 2012-08-17 15:47:05.663 2013-07-17 15:47:05.663 2012-07-16 15:47:05.663 2012-06-17 15:47:05.663 2011-07-17 15:47:05.663

select

datediff(dd,'

2012-07-11 15:03:11.623

',getdate()) --

時間差--

6select

datename(dayofyear,getdate()) ,datediff(dd,'

2012-01-01

',getdate

())--

199 198

select

datename(year, getdate

())

,datename(month, getdate

())

,datename(day, getdate

())

,datename(week,getdate

())

,datename(dayofyear, getdate

()) ,

datename(weekday, getdate

()); --

2012 july 17 29 199 tuesday

select

datename(hour, getdate()) --

當天的第幾個小時

,datename(minute,getdate()) --

當天小時的第幾分

,datename(second, getdate()); --

當天小時分鐘的第幾秒

---15 48 9

select

isdate('

2012-07-17

') union

allselect

isdate('

2012-07-17 15:12:00

') union

allselect

isdate(111)/*

110*/

/*函式 語法 返回值 返回資料型別

day day ( date ) 返回表示指定 date 的「日」部分的整數。 int 具有確定性

month month ( date ) 返回表示指定 date 的「月」部分的整數。 int 具有確定性

year year ( date ) 返回表示指定 date 的「年」部分的整數。 int 具有確定性

datename datename ( datepart , date ) 返回表示指定日期的指定 datepart 的字串。 nvarchar

datepart datepart ( datepart , date ) 返回表示指定 date 的指定 datepart 的整數。 int

datediff datediff ( datepart , startdate , enddate ) 返回兩個指定日期之間所跨的日期或時間 datepart 邊界的數目。 int 具有確定性

dateadd dateadd (datepart , number , date ) 通過將乙個時間間隔與指定 date 的指定 datepart 相加,返回乙個新的 datetime 值。

isdate isdate ( expression ) 確定 datetime 或 smalldatetime 輸入表示式是否為有效的日期或時間值。

int 只有與 convert 函式一起使用,同時指定了 convert 樣式引數且樣式不等於 0、100、9 或 109 時,isdate 才是確定的。

*/

T SQL 日期常用函式

environment win7 sql server 2008 r2 author cc desctiption 常用日期函式整理 day,month,year datepart dateadd,datename datediff isdate 的使用 擷取乙個時間的年,月,日 select da...

常用函式 日期函式

對日期的處理,一般在有日期限制的共享 商業軟體中經常使用到。如果你打算編寫一款有日期限制的軟體,熟悉使用下面的函式即可以實現。1.date 功能說明 返回當前的日期。procedure tform1.button1click sender tobject begin label1.caption 今...

T SQL常用的字串函式

常用的字串函式有 一 字元轉換函式 1 ascii 返回字元表示式最左端字元的ascii 碼值。在ascii 函式中,純數字的字串可不用 括起來,但含其它字元的字串必須用 括起來使用,否則會出錯。2 char 將ascii 碼轉換為字元。如果沒有輸入0 255 之間的ascii 碼值,char 返回...