SQL Server 自定義DateTime格式化顯示內容

SQL Server的Convert函數沒有想要的格式類型,需要自定義顯示格式。

CAST and CONVERT (Transact-SQL)

These functions convert an expression of one data type to another.
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

FORMAT (Transact-SQL)

Returns a value formatted with the specified format and optional culture. Use the FORMAT function for locale-aware formatting of date/time and number values as strings. For general data type conversions, use CAST or CONVERT.
https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql

SELECT FORMAT(GETDATE(), N'dd/MM/yyyy hh:mm tt')

顯示結果

09/03/2023 05:19 PM

如果直接運行

SELECT FORMAT(NULL, N'dd/MM/yyyy hh:mm tt')

會報錯,但是如果是一個表中的datetime字段的值爲null,結果也會返回null,不會報錯。

select FORMAT(<datetime column name>, N'dd/MM/yyyy hh:mm tt') from <tableName>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章