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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章