善用 SQL Server 中的 CONVERT 函數處理日期字串
selectconvert(varchar(4),Year(getdate())) + '-' + convert(varchar(2), month(getdate()))+ '-' + convert(varchar(2), day(getdate()))
select
convert(varchar(4),Year(getdate())) + '-'
+
CASEmonth(getdate())
WHEN 1 THEN'0' + convert(varchar(2),
month(getdate()))
WHEN 2 THEN'0' + convert(varchar(2),
month(getdate()))
WHEN 3 THEN'0' + convert(varchar(2),
month(getdate()))
WHEN 4 THEN'0' + convert(varchar(2),
month(getdate()))
WHEN 5 THEN'0' + convert(varchar(2),
month(getdate()))
WHEN 6 THEN'0' + convert(varchar(2),
month(getdate()))
WHEN 7 THEN'0' + convert(varchar(2),
month(getdate()))
WHEN 8 THEN'0' + convert(varchar(2),
month(getdate()))
WHEN 9 THEN'0' + convert(varchar(2),
month(getdate()))
ELSEconvert(varchar(2), month(getdate())) END+
'-'
+
CASEday(getdate())
WHEN 1 THEN'0' + convert(varchar(2),
day(getdate()))
WHEN 2 THEN'0' + convert(varchar(2),
day(getdate()))
WHEN 3 THEN'0' + convert(varchar(2),
day(getdate()))
WHEN 4 THEN'0' + convert(varchar(2),
day(getdate()))
WHEN 5 THEN'0' + convert(varchar(2),
day(getdate()))
WHEN 6 THEN'0' + convert(varchar(2),
day(getdate()))
WHEN 7 THEN'0' + convert(varchar(2),
day(getdate()))
WHEN 8 THEN'0' + convert(varchar(2),
day(getdate()))
WHEN 9 THEN'0' + convert(varchar(2),
day(getdate()))
ELSEconvert(varchar(2), day(getdate())) END
[/code]
別笑,!我真的看過有人這樣寫!呵呵~
其實SQL Server 早就有個CONVERT 函數可以幫我們做這件事,!如果你要輸出2008-02-27 這種日期格式的字串,,可以這樣寫:
[code:tsql]
SELECTCONVERT(char(10), getdate(), 120)
[/code]
是不是短很多呢?^__^
底下列出一些我常用的語法:
- 輸出格式:2008-02-27 00:25:13
SELECT CONVERT(char(19), getdate(), 120) - 輸出格式:2008-02-27
SELECT CONVERT(char(10), getdate(), 20)
- 輸出格式:2008.02.27
SELECT CONVERT(char(10), getdate(), 102) - 輸出格式:08.02.27
SELECT CONVERT(char(8), getdate(), 2) - 輸出格式:2008/02/27
SELECT CONVERT(char(10), getdate(), 111) - 輸出格式:08/02/27
SELECT CONVERT(char(8), getdate(), 11) - 輸出格式:20080227
SELECT CONVERT(char(8), getdate(), 112) - 輸出格式:080227
SELECT CONVERT(char(6), getdate(), 12)
想查詢完整的列表與說明可以到MSDN 的Transact-SQL Reference 去查詢CAST and CONVERT 的詳細說明,。