使用SQL Sever语言进行数据库的操作

常用关键字
identity 自增长
primary key 主键
unique 唯一键
not null 非空
references 外键(引用)

在使用查询操作数据库是,要设置好需要操作的数据库,避免出现错误


1、删除表
drop table 表名
2、修改表
alter table 表名 add 列名 数据类型 ---追加
alter table 表名 drop column 列名


CRUD操作 ☆★☆

create 添加数据
read 读取数据
update 修改数据
delete 删除数据

1、添加数据
insert into 表名 value(```,```) 有几列加几列,不能遗漏

insert into 表名(列名,列名2) value(```,```) 改哪列表名后面加哪列

SQL Server中第一列如果是自增长列,那么添加时第一列可以忽略
其他数据库需要留空

2、删除数据
delete from 表名 逻辑上可行,运行删除删除所有数据,实际使用时禁止。

delete from 表名 where ids=5 删除ids=5这一行


3、修改数据
update 表名 set fcode='p016' 修改所有fcode的数据
update 表名 set fcode='p016' where ids=6 修改ids=5的fcode的数据
update 表名 set fcode='p016',mcode='p002' where ids=6


SQL中,布尔型的数据也需要加单引号

 

 

查询

1、简单查询

select * from 表名 --查询所有数据,*代表所有列

select 列名,列名 from 表名 --差指定列的数据,要查多列用逗号分隔

select 列名 as '代号’',列名 as '姓名' from 表名 --给列指定别名


2、条件查询

select * from 表名 where 条件

select * from 表名 where 条件 and 条件 --多条件并的关系

select * from 表名 where 条件 or 条件 --多条件或的关系

3、范围查询
select * from 表名 where 范围
例子:select * from 表名 where price>40 and price<50
同:select * from 表名 where price between 40 and 50

4、离散查询
select * form 表名 where 列名 in ('值','值','值')

select * form 表名 where 列名 not in ('值','值','值')


5、模糊查询

关键字查询

select * from 表名 where 列名 like '%关键字%' --%代表任意多个字符,%关键字 
% 查询包含所写关键字的行,关键字% 查询以关键字开头的行,%关键字 查询以关键 
字结尾的行,关键字 查询等于关键字的行


select * from 表名 where 列名 like '__E%' --查询第三个字符是E的

_代表一个字符


6、排序查询

select * from 表名 order by 列名 --根据by后面的列里的数据进行排序,默认是 
升序

select * from 表名 order by 列名 desc --desc代表降序,asc 代表升序


select * from 表名 order by 列名 desc,列名 asc --先根据第一个条件排序,相 
同的再根据第二个条件排序。前是主条件,后面是次要条件

7、分页查询

select top 数目 * from 表名

select top 数目 * from 表名 where 别名 not in (select top 数目 列名 from 
表名)


例子:
当前页:page = 2;每页显示:row = 10;
select top 5 * from Car where Code not in (select top (page-1)*row Code 
from Car)


8、去重查询

select distinct 别名 from 表名 --把重复的去掉

9、分组查询
select * from 表名 group by 列名 having count(*)>2
根据列名 进行分组,条件是数量大于2 count(*)代表个数

10、聚合函数(统计查询)

select count(*) from 表名 --查询所有数据条数

select count(列名) from 表名

select sum(列名) from 表名 --查询总和

select avg(列名) from 表名 --查询平均

select max(列名) from 表名 --查询最大值

select min(列名) from 表名 --查询最小值

 

关键字不区分大小写

posted on 2016-08-08 16:24  Lovetolaugh  阅读(833)  评论(0编辑  收藏  举报