Ø 简介
本文主要列举 SQL Server 中常用的一些系统函数,帮助我们在编写 SQL 时忘了某个函数的用法方便查阅。主要分为以下几类函数,更多函数可参考官网。
1. 字符串函数
2. 日期函数
3. 数学函数
4. 其他函数
1. 字符串函数
Ø 提示:SQL Server 中的字符串索引始终从1开始。
1) CHARINDEX()
语法:CHARINDEX(expressionToFind, expressionToSearch[, start_location])
描述:返回第一个表达式在第二个表达式中第一次出现的起始位置,不存在返回零。示例:SELECT (不包括 0 和 1)之间的伪随机 float 值。注意:相同的种子,随机数始终一致。
示例:ELECT RAND() AS Column1, RAND() AS Column2, RAND(100) AS Column3, RAND(100) AS Column4;
结果:
3) ROUND()
语法:ROUND(numeric_expression, length[, function])
描述:返回一个数值,舍入到指定的长度或精度。
示例:SELECT ROUND(12, 2) AS Column1, CAST(ROUND(12, 2) AS numeric(19,2)) AS Column2, ROUND(12.2346, 2) AS Column3, ROUND(12.2356, 2) AS Column4, ROUND(12.2354, 2) AS Column5, ROUND(748.58, -2) AS Column6, ROUND(150.75, 0) AS Column7, ROUND(150.75, 0, 1) AS Column8;
结果:
4) CEILING()
语法:CEILING(numeric_expression)
描述:此函数返回大于或等于指定数值表达式的最小整数。
示例:SELECT CEILING(1.48) AS Column1, CEILING(14.32) AS Column2, CEILING(44.98) AS Column3;
结果:
5) FLOOR()
语法:FLOOR(numeric_expression)
描述:返回小于或等于指定数值表达式的最大整数。
示例:SELECT FLOOR(1.48) AS Column1, FLOOR(14.32) AS Column2, FLOOR(44.98) AS Column3;
结果:
4. 其他函数
1) CAST()
语法:CAST(expression AS data_type[(length)])
描述:这些函数将表达式由一种数据类型转换为另一种数据类型。
示例:SELECT 9.5 AS Original, CAST(9.5 AS int) AS int, CAST(9.5 AS decimal(6,4)) AS decimal;
结果:
2) CONVERT()
语法:CONVERT(data_type[(length)], expression[, style])
描述:这些函数将表达式由一种数据类型转换为另一种数据类型。
示例:SELECT 9.5 AS Original, CONVERT(int, 9.5) AS int, CONVERT(decimal(6,4), 9.5) AS decimal;
结果:
Sytle 参数示例:SELECT GETDATE() AS Original, CONVERT(varchar(128), GETDATE(), 8) AS [style is 8], CONVERT(varchar(128), GETDATE(), 14) AS [style is 14], CONVERT(varchar(128), GETDATE(), 11) AS [style is 11], CONVERT(varchar(128), GETDATE(), 111) AS [style is 111], CONVERT(varchar(128), GETDATE(), 23) AS [style is 23], CONVERT(varchar(128), GETDATE(), 12) AS [style is 12], CONVERT(varchar(128), GETDATE(), 112) AS [style is 112], CONVERT(varchar(128), GETDATE(), 102) AS [style is 102], CONVERT(varchar(128), GETDATE(), 20) AS [style is 20], CONVERT(varchar(128), GETDATE(), 21) AS [style is 21];