標籤:
上面幾個函數都是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 intSET @Year = 2012SET @Month = 02SET @Day = 30SELECT DATEFROMPARTS (@Year, @Month, @Day) AS MyDate
結果就是
Msg 289, Level 16, State 1, Line 61Cannot construct data type date, some of the arguments have values which are not valid.
如果是合法
DECLARE @Year int, @Month int, @Day intSET @Year = 2012SET @Month = 02SET @Day = 28SELECT 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 intSET @Hour = 15SET @Minutes = 23SET @Seconds = 47SET @FractionsOfASecond = 500SELECT TIMEFROMPARTS(@Hour, @Minutes, @Seconds, @FractionsOfASecond, 3) AS MyTime
結果
15:23:47.500
如果傳入一個NULL值呢
DECLARE @Hour int, @Minutes int, @Seconds int,@FractionsOfASecond intSET @Hour = 15SET @Minutes = 23SET @Seconds = 47SET @FractionsOfASecond = 500SELECT TIMEFROMPARTS(@Hour, @Minutes, @Seconds, NULL, 3) AS MyTime
結果也是NULL
DATETIMEFROMPARTS
這個就是前面兩個的結合。特點也就是傳入NULL值就是結果變NULL,不合法值就報錯。奇怪的是它沒有了TIMEFROMPARTS的精確位元參數。
DECLARE @Year int, @Month int, @Day int, @Hour intDECLARE @Minutes int, @Seconds int, @MilliSeconds intSET @Year = 2012SET @Month = 07SET @Day = 23SET @Hour = 17SET @Minutes = 27SET @Seconds = 49SET @MilliSeconds = 0SELECT 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 intDECLARE @Hour int, @Minutes int, @Seconds intDECLARE @FractionsOfASecond intDECLARE @HourOffSet int, @MinuteOffSet intSET @Year = 2012SET @Month = 02SET @Day = 26SET @Hour = 15SET @Minutes = 57SET @Seconds = 49SET @FractionsOfASecond = 500SET @HourOffSet = 7SET @MinuteOffSet = 30SELECT DATETIMEOFFSETFROMPARTS (@Year, @Month, @Day, @Hour,@Minutes, @Seconds, @FractionsOfASecond, @HourOffSet,@MinuteOffSet, 3) AS MyTimeZone
SQL Server ->> 時間函數: EOMONTH, DATEFROMPARTS, TIMEFROMPARTS, DATETIMEFROMPARTS, DATETIMEOFFSETFROMPARTS