跳轉到內容

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].

left, right, 和 substring

[編輯 | 編輯原始碼]

允許根據字串中某些字元的位置進行擷取[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)

replace 和 stuff

[編輯 | 編輯原始碼]

搜尋和替換:允許根據其值替換某些字串字元[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]

  • DATEDIFF 計算兩個日期之間的間隔[8].
  • DATEADD 返回另一個日期加上一個間隔的結果日期[9].
-- 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

參考資料

[編輯 | 編輯原始碼]
  1. CONVERT 手冊
  2. http://stackoverflow.com/questions/74385/how-to-convert-datetime-to-varchar
  3. SUBSTRING 手冊
  4. STUFF 手冊
  5. REPLACE 手冊
  6. DATEPART 手冊
  7. http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/
  8. DATEDIFF 手冊
  9. DATEADD 手冊
華夏公益教科書