Microsoft SQL Server/函式
外觀
Min() 和 Max() 函式分別返回一個欄位列表中的最小值和最大值。
select min(Date) from Calendar where RDV = 'Important'
修改變數型別
cast(Champ as decimal(12, 6)) -- otherwise '9' > '10'
在第一個引數中修改變數型別,在第二個引數中修改其長度。
convert(varchar, Field1, 112)
convert(datetime, Field2, 112) -- otherwise impossible to go through the calendar (eg: D + 1)
注意:所有變數型別之間並不相容[1].
問題示例
select Date1
from Table1
where Date1 between '01/10/2013' and '31/10/2013'
如果沒有 convert,日期不會被系統識別。解決方案是將它們儲存在 datetime 格式中
select Date1
from Table1
where Date1 between convert(varchar,'20131001',112) and convert(varchar,'20131031',112)
另一方面,如果上面的日期段以斜槓的形式儲存在 varchar 中,那麼必須將其重新格式化才能進行比較。
有許多日期格式可用[2].
允許根據字串中某些字元的位置進行擷取[3].
select substring('13/10/2013 00:09:19', 7, 4) -- returns the hour character after the seventh, so "2013"
例如,在上面的斜槓日期的情況下
select Date1
from Table1
where right(Date1, 4) + substring(Date1, 4, 2) + left(Date1, 2) between convert(varchar,'20131001',112) and convert(varchar,'20131031',112)
搜尋和替換:允許根據其值替換某些字串字元[4].
例如,更新給定的資料夾路徑[5]
update Table1
SET Field1 = replace(Field1,'\Old_path\','\New_path\')
where Field1 like '%\Old_path\%'
如果變數為 null,則返回 true。
select Field1 = case when isnull(@Column,'')='' then '*' else @Column end
from Table1
GETDATE 函式用於獲取當前日期。要以正確的格式獲取另一個日期,需要使用 CONVERT
select convert(smalldatetime, '2016-01-02', 121)
DATEPART 函式提取日期的一部分,而無需手動指定其位置[6].
然而,三個函式允許加速這些提取的編寫
-- Day
select day(getdate())
-- Month
select month(getdate())
-- Year
select year(getdate())
-- Previous year
select str(year(getdate()) - 1)
這裡有兩個日期操作函式[7]
-- Last day of the previous month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
-- Last day of the current month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
-- Last day of the previous month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
示例
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,'20150101'),0)) as date
給出
date 2014-12-31 23:59:59.000