码迷,mamicode.com
首页 > 数据库 > 详细

SQL_server 的基本操作

时间:2014-07-21 08:30:19      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:des   使用   数据   for   re   c   


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‘(备份到的路径)

SQL_server 的基本操作,布布扣,bubuko.com

SQL_server 的基本操作

标签:des   使用   数据   for   re   c   

原文地址:http://www.cnblogs.com/sunxun/p/3856398.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!