SQL_server 的基本操作
1.---------------数据库基本操作
主键 : 1.不重复 2.不为NULL
外键
1.取消重复行(消除完全一样的行,保留一行)
select distinct cloumname1,cloumname2 from tablename
2.区间查询(两种是一个意思)
select * from emp where sal > 2000 and sal < 2500
select * from emp where sal between 2000 and 2500(效率会高一点)
3. 模糊查询
select * from emp where name like ‘%s%‘
(查询name 的第三个是s的行记录,_匹配任意单个字符串)
select * from emp where name like ‘__s%‘
4.批量查询(两种相同,一个是针对多种情况,一个是针对少数情况)
select * from emp where empno = ‘123‘ or empno = ‘234‘ or empno = ‘456‘
select * from emp where empno in (‘123‘,‘234‘,‘456‘)
5.顺序
select * from emp order by empno ASC(升序)
select * from emp order by empno DESC(降序)
select * from emp order by empno DESC,sal ASC
6.别名排序
select sal*12 as count_sal from emp order by count_sal
7.分组查询
select max(sal),deptno from emp group by deptno
having 可以对分组查询到的结果进行筛选
select max(sal) from emp group by deptno having sal < 2000
8.多表查询
select * from emp,dept,dept.deptno where dept.dname = ‘sun‘ and emp.no = dept.no;
(取别名查询,加快sql的执行速度)
select * from emp e,dept d where d.dname = ‘sun‘ and e.no = d.no;
9.内连接
select emp.name,dept.name from emp,dept where emp.no = dept.no
10.单行子查询和多行子查询
要知SQL里面能返回多条记录集,可以内连接的时候却是不能循环的。
所以,要在SQL里面使用循环,
单行子查询
select * from emp where job = (select job from emp where depton = ‘10‘)
多行子查询
select * from emp where job in (select job from emp where depton = ‘10‘)
把查询到的结果当做一个临时表
select emo.ename ,emp.sal tem.myavg from emp,(select avg(sal) myavg.deptno from emp group by deptno ) tem where emp.deptno = tem.deptno and emp.sal > tem.myavg
11.分页查询
前几个
select top 4 * from emp order by clownname
不在某个范围的前几个
select top 4 * from emp where empno not in (
select top 10 empno from emp order by clownname
)order by clownname
12.删除一个表的重复语句
select distinct *(选择一个字段,) into(到一个临时表中去) #temp from cat
delete from cat
insert into cat from select * from #temp
drop table #temp
13.外连接(左连接,右连接)
select w.ename,b.ename from emp w left t join emp b on w.mgr = b.empno
左外连接指:左边的表记录全部显示,没有匹配的记录,没有匹配的记录用NULL填
-----------2.约束
not null (非空) null 和 ‘‘不一样
unique (唯一)--和主键不一样,都不允许重复,unique能放空(可是只能有一个空),主键不能放空
primary key (主键)主键只能有一个,不过可以有组合主键,就是字段联合做主键
复合主键
primary key (clownname1,clownname2)
foreign key (外键)定义主表和从表之间的关系,定于在从表上
check (范围) clownname int ckeck(clownname > 1000 and clownname <25000)
default(默认)
3.-----
备份数据库
backup database dataname(数据库名) to disk = ‘f:/sp.bak‘(备份到的路径)
删除数据库
drop database dataname
恢复数据库
restore database dataname(数据库名) from disk = ‘f:/sp.bak‘(备份到的路径)
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。