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>