SQL连接符、表达式及函数

连接符

+ 连接符

连接表中数据类型相同或近似的列,若数据类型完全不同,则需通过CAST表达式进行类型转换,若其中一列为NULL则结果为NULL

1
2
3
4
5
6
SELECT 
TOP 3
new_country_idName + '--' +new_city_idName AS Adress,
Name
FROM
Account

表达式

CAST表达式

转换数据类型,若数据为空则转换结果为NULL

1
2
3
4
5
6
7
8
9
SELECT 
TOP 3
new_country_idName + '--' +new_city_idName AS Adress,
Name + new_age AS Mesg
FROM
Account


> [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]从数据类型 nvarchar 转换为 numeric 时出错。 (8114)
1
2
3
4
5
6
SELECT 
TOP 3
new_country_idName + '--' +new_city_idName AS Adress,
Name + CAST(new_age AS VARCHAR(256)) AS Mesg
FROM
Account

CASE表达式

1
2
3
4
5
6
7
8
9
10
11
SELECT 
TOP 3
new_country_idName + '--' +new_city_idName AS Adress,
Name,
CASE
WHEN Name = '李老板' THEN '李老板好'
WHEN Name = '高永平' THEN '高老板好'
ELSE '您好'
END AS Say
FROM
Account

函数

对列中某个数据进行处理并返回值

字符串操作函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
---字符中操作函数
UPPER(S) 将字符串统一为大写字母
SELECT UPPER('asasA') --ASASA

LOWER(S) 将字符串统一为小写字母
SELECT LOWER('asasA') ---asasa

LEN(S) 返回字符串的长度
SELECT LEN('中国1号') --4

CHARINDEX(S1,S2) 返回S1在字符串S2中的位置
SELECT CHARINDEX('aa1号','1111aa1号中国1号') --5

SUBSTRING(S,I,N) 在S字符串中的第I个字符起取N个字符
SELECT SUBSTRING('TECHNOLO',3,3) --CHN


SELECT CONVERT(INT,'111')

LEFT(S,N) 从字符串S左边取N个字符
RIGHT(S,N) 从字符串S右边取N个字符
SELECT RIGHT('00000000'+'11',8)
SELECT RIGHT('00000000'+'2222',8)
SELECT LEFT('11'+'00000000'+'11',8)
SELECT LEFT('2222'+'00000000'+'2222',8)

SPACE(N) 生成N个空格
SELECT '合计'+SPACE(2)+'123'

RTRIM(S) --消除字符串左边开始或者右边开始的空格
LTRIM(S) --消除字符串左边开始或者右边开始的空格


SELECT RTRIM(' SAMPLE ')
SELECT LTRIM(' SAMPLE ')
SELECT LTRIM(RTRIM(' SAMPLE '));


REPLACE(STRING,ATOREPLACE,NEWSTRING) --替换函数
SELECT REPLACE('HHAAAH','A','S')

数学函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
abs(numeric_expr) --求绝对值
ceiling(numeric_expr) --取大于等于指定值的最小整数
exp(float_expr) --取指数
floor(numeric_expr) --小于等于指定值得最大整数
power(numeric_expr,power) --返回power次方
rand([int_expr]) --随机数产生器
round(numeric_expr,int_expr) --安int_expr规定的精度四舍五入
sign(int_expr) --根据正数,0,负数,,返回+1,0,-1
sqrt(float_expr) --平方根
exp(float x) --求e的x次幂
tan(float x) --计算x(弧度表示)的正切值。
atan(float x) --求x(弧度表示)的反正切值
cos(float x) --求x(弧度表示)的余弦值
acos(float x) --求x(弧度表示)的反余弦值
sin(float x) --计算x(弧度表示)的正弦值。
asin(float x) --求x(弧度表示)的反正弦值
fabs(float x) --求浮点数x的绝对值
fmod(float x, float y) --计算x/y的余数
pow(float x, float y) --计算x的y次幂。
sqrt(float x) --计算x的平方根。

日期函数

1
2
3
4
5
6
getdate() --返回日期
datename(datepart,date_expr) --返回名称
datepart(datepart,date_expr) --取日期一部份
datediff(datepart,date_expr1.dateexpr2) --日期差
dateadd(datepart,number,date_expr) --返回日期加上 number
day(date_expr), month(date_expr),year(date_expr) --提取date_expr中的日月年
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020 李明华
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信