1. 程式人生 > >SQL Server ->> 時間函式: EOMONTH, DATEFROMPARTS, TIMEFROMPARTS, DATETIMEFROMPARTS, DATETIMEOFFSETFROMPARTS

SQL Server ->> 時間函式: EOMONTH, DATEFROMPARTS, TIMEFROMPARTS, DATETIMEFROMPARTS, DATETIMEOFFSETFROMPARTS

原文: SQL Server ->> 時間函式: EOMONTH, DATEFROMPARTS, TIMEFROMPARTS, DATETIMEFROMPARTS, DATETIMEOFFSETFROMPARTS

上面幾個函式都是SQL Server 2012新增的時間函式。

 

EOMONTH

返回傳入時間的月結束日,返回資料型別為DATE

SELECT EOMONTH(GETDATE())

結果為

2016-01-31

 

DATEFROMPARTS

如同C#或者Java宣告一個DATETIME例項那樣通過傳入YEAR, MONTH, DAY的數字值得到一個DATETIME的例項。這裡也是一樣。通過傳入年月日來得到一個DATE。但是如果你一旦傳入的引數無法構造出一個合法的時間,就會報錯。

DECLARE @Year int, @Month int, @Day int
SET @Year = 2012
SET @Month = 02
SET @Day = 30
SELECT DATEFROMPARTS (@Year, @Month, @Day) AS MyDate

結果就是

Msg 289, Level 16, State 1, Line 61
Cannot construct data type date, some of the arguments have values which are not valid.

 

如果是合法

DECLARE
@Year int, @Month int, @Day int SET @Year = 2012 SET @Month = 02 SET @Day = 28 SELECT DATEFROMPARTS (@Year, @Month, @Day) AS MyDate

那就是

2012-02-28

 

TIMEFROMPARTS

和DATEFROMPARTS類似,只不過傳入的變成HOUR, MINUTE, SECOND,MILLISECOND和MILLISECOND精確位數,然後返回的是一個TIME型別。有一個需要注意的是這個函式的第五個引數是不支援整型變數的,必須是顯示常量傳入。

 

比如

DECLARE @Hour int, @Minutes int, @Seconds int,
@FractionsOfASecond int

SET @Hour = 15
SET @Minutes = 23
SET @Seconds = 47
SET @FractionsOfASecond = 500

SELECT TIMEFROMPARTS(@Hour, @Minutes, @Seconds, @FractionsOfASecond, 3) AS MyTime

結果

15:23:47.500

 

如果傳入一個NULL值呢

DECLARE @Hour int, @Minutes int, @Seconds int,
@FractionsOfASecond int

SET @Hour = 15
SET @Minutes = 23
SET @Seconds = 47
SET @FractionsOfASecond = 500

SELECT TIMEFROMPARTS(@Hour, @Minutes, @Seconds, NULL, 3) AS MyTime

結果也是NULL

 

DATETIMEFROMPARTS

這個就是前面兩個的結合。特點也就是傳入NULL值就是結果變NULL,不合法值就報錯。奇怪的是它沒有了TIMEFROMPARTS的精確位數引數。

 

DECLARE @Year int, @Month int, @Day int, @Hour int
DECLARE @Minutes int, @Seconds int, @MilliSeconds int
SET @Year = 2012
SET @Month = 07
SET @Day = 23
SET @Hour = 17
SET @Minutes = 27
SET @Seconds = 49
SET @MilliSeconds = 0
SELECT DATETIMEFROMPARTS (@Year, @Month, @Day, @Hour, @Minutes,
@Seconds, @MilliSeconds) AS MyDateTime

結果

2012-07-23 17:27:49.000

 

DATETIMEOFFSETFROMPARTS

這個比較有意思。加入了TIMEZONE。

DECLARE @Year int, @Month int, @Day int
DECLARE @Hour int, @Minutes int, @Seconds int
DECLARE @FractionsOfASecond int
DECLARE @HourOffSet int, @MinuteOffSet int
SET @Year = 2012
SET @Month = 02
SET @Day = 26
SET @Hour = 15
SET @Minutes = 57
SET @Seconds = 49
SET @FractionsOfASecond = 500
SET @HourOffSet = 7
SET @MinuteOffSet = 30

SELECT DATETIMEOFFSETFROMPARTS (@Year, @Month, @Day, @Hour,
@Minutes, @Seconds, @FractionsOfASecond, @HourOffSet,
@MinuteOffSet, 3) AS MyTimeZone