1_Sql 里面常用的函数
函数 | 说明 |
---|---|
Count() | 计数 |
len() | 长度 |
str() | 将数值转换为字符数据,可以指定长度和精度 |
cast() | 实现数据类型的显示转换 |
convert() | 类型转换 + 格式化(非标准扩展) |
getdate() | 获取当前时间 |
rand() | 产生0-1之间的随机小数,不包括0和1 |
round() | 四舍五入取整 |
sum() | 求和 |
max() | 最大值 |
min() | 最小值 |
avg() | 平均值 |
row_number | 对查到的数据进行重新编号,赋予他来连续的编号 |
over | 依据 |
(1)Count 计数
sql
select Count(*) from Students;-- 返回Students表中行数
select count(distinct customer_id) from orders--不重复客户数
(2)len():长度
sql
select len('张三')--2
select len(StuName) from Students--返回Students表中每个StuName的长度
(3)str():将数值转换为字符数据,可以指定长度和精度,
参数1为需要转换的数值,
参数2为最多字符串的总长度(包含数字和小数点,空格),默认为10
参数3为小数的位数,默认为0
注:如果指定的 length 小于数值的实际长度,会返回 ** 表示溢出。 结果字符串会靠右对齐,不足的长度会用空格填充。
sql
select str(123.12345,6,2)--123.12
select str(123.12345,8,3)--123.123
select str(123.12345,10,3)--123.123
(4)cast():实现数据类型的显示转换
sql
select cast('2024-09-10' as date); -- 字符串 → 日期
select cast(quantity as varchar(50))from t; -- 数字 → 字符串
(5)convert():类型转换 + 格式化(非标准扩展)
sql
select convert(varchar,getDate(),120);-- 2025-08-21 15:30:00
(6)getdate():获取当前时间
sql
select getdate();
(7)rand(): 产生0-1之间的随机小数,不包括0和1;产生x-y之间的随机数 rand() * (y-x)+x;
sql
declare @rand int;
set @rand=rand()*(100-60)+60
2_Sql中的运算符
(1)sql中许多运算符与C#中类似,下面列举与c#中不同的并于c#中做对比
运算符 | sql | c# |
---|---|---|
= | 等于 | 赋值 |
<> | 不等于 | != |
and | 和 | && |
or | 或 | || |
Not | 取反 | ! |
between | 如果操作数在某个范围之内,则结果为 TRUE | |
in | 表达式的值是否在指定的列表或子查询结果中 | |
like | 字符串模式匹配的运算符 |
3_常用关键字
关键字 | 作用 |
---|---|
declare | 定义变量 |
set | 给变量赋值 |
distinct | 查询时返回唯一不同的值 |
alter | 修改现有数据库对象的结构 |
while | 循环 |
示例
sql
sql
-- Sql 声明变量
declare @a int;
-- sel中赋值 : 两种语法 set| select
select @a=100;
select @a-=100;
set @a+=100;
set @a=@a+100;
-- 打印
print @a;
--字符串 拼接
select 'abc'+'defg' as newString
--distinct
select distinct City from Customers;
--alter
alter table TableName add Email varchar(50)