http://www.cnblogs.com/rainman/archive/2013/05/03/3058451.html
create database CherryTest;
–表操作
–建表(多行注释使用/*注释*/)
use CherryTest;
create table person
(_id int primary key,
name varchar(20),
birthday date,
salary decimal,
sex bit)
–sqlserver中没有bool型,但有bit型,只能存0或1或空
–删表
drop table person;
–修改表
–改表名
exec sp_rename ‘person’,’Person’;
–增列
Alter table person add hobby varchar(100);
–减列
Alter table person drop column hobby;
–改列
Alter table person alter column name varchar(100);–改列类型
Alter table person add constraint uniqueName unique (name);–为列添加唯一约束
Alter table Person add constraint defdept default(10) for departId;–添加默认值
exec sp_rename ‘Person.birthday’,’birth’,’column’;–改列名(原列名一定要带表名前缀)
–本句所执行的为系统自带存储过程(exec sp_rename ‘stud.name’, ‘sName’, ‘column’;)
–建视图
–(在 SQL 中,视图是基于 SQL 语句的结果集的可视化的表。即一个或多个表查询所得的数据构成的表)
–要有数据才好筛选,所以要先执行下面的DML语句
Insert into Person values(1,’cherry’,’1994-01-12’,5000,0);
Insert into Person values(2,’cherry2’,’1994-01-12’,4000,0);
Insert into Person values(3,’cherry3’,’1994-01-12’,3000,1);
CREATE VIEW myView AS
SELECT name,birth
FROM Person
WHERE sex!=0
–删视图
drop view myview;
–修改视图
ALTER VIEW myView
AS
select name,birth,_id from Person
Where sex=0
–建好视图后其使用与表类似
select * from myview;
–建存储过程
–(类似于Java语言中的方法,是一组为了完成特定功能的SQL语句集合,经编译后存储在数据库中,用户通
过指定存储过程的名称并给出参数来执行)
–sys.objects(保存当前数据库的对象。如约束、默认值、日志、规则、存储过程等)
if (exists (select * from sys.objects where name = ‘proc_get_person’))
drop proc proc_get_person
go
–判断是否已存在该存储过程(也可用if (object_id(‘proc_findStudentByName’, ‘P’) is not null))
create proc proc_get_person
as
select * from Person
–创建带参数的存储过程(可为输出参数,在参数后加out关键字即可)
create proc proc_find_person(@startId int, @endId int)
as
select * from Person where _id between @startId and @endId
exec proc_find_person 2, 4;
–修改存储过程
alter proc proc_find_person
as
select * from student;
–删除存储过程
drop proc proc_find_person
–建函数
/*
Create function 函数名(参数)
Returns 返回值数据类型
[with {Encryption | Schemabinding }]
[as]
begin
SQL语句(必须有return 变量或值)
End
*/
—实例
Create function AvgSalary(@name varchar(10))
Returns decimal
As
Begin
Declare @avg decimal
Declare @fullName varchar(11)
Set @fullName=@name+’%’
Select @avg=avg(salary) from Person
Where @name like @fullName
Return @avg
End
–执行
select dbo.AvgSalary(‘cherry’) as result –dbo.前缀必须有,因为不是系统自定义函数
–@avg=avg(salary)意为将salary的平均值赋给avg参数,dbo是当前用户名
–增删改:
Insert into Person(_id,name) values(10,’cherry10’);
delete from Person where salary<4000;
update Person set birthday=’1999-01-01’,salary=10000 where _id=10;
–查
—先建立连接所需的第二张表Department
use CherryTest;
create table Department
(_departId int primary key,
departName varchar(20),
)
Insert into Department values(10,’tech’);
在第一张person表上添加部门号
Alter table Person add departId int;
Insert into Person values
(11,’cherry11’,’1994-01-12’,5000,0,10);
–内连接查询
–(只选交集)
select * from Person ,Department
where Person .departId =Department ._departId
–或者
Select * from Person
JOIN Department ON
Person.departId=Department ._departId
—左外连接(交集和左表中没入选的(配对的右表数据为空))
Select * from Person
Left JOIN Department ON
Person.departId=Department ._departId
—右外连接(交集和右表中没入选的(配对的左表数据为空))
Select * from Person
Right JOIN Department ON
Person.departId=Department ._departId
–子查询
–in
SELECT name ,birthday ,salary
FROM Person
WHERE departId in
( SELECT _departId
FROM Department
WHERE
departName LIKE ‘t%’);
–此处为in代表集合,可为=代表定值,还可以是><(对于数值型字段),
–还可以是多列子查询,where (字段1,字段2) in(select 字段1,字段2 from ……)
–内联子查询(from后面不跟表名而跟select语句)
–exists返回值True或False,指定子查询检测行是否存在(所以select后一般不跟字段,直接用*)
–select * from a where exists(select * from b where id=a.id),如果select * from b where id=a.id这一句能查
出来数据,那么查出来的a表中的数据是这样写是一样的:select * from a where id in(select id from b);
SELECT name ,birthday ,salary
FROM Person
WHERE exists
( SELECT * FROM Department
WHERE _departId =
Person.departId);
相当于
SELECT name ,birthday ,salary
FROM Person
WHERE departId in
( SELECT _departId FROM Department);
–exsits后的语句与前表无关怎么办?(就相当于没有where子句,查询全部)
–不存在此情况,exists,相关子查询,in 相关或不相关
–not in not exists分别是 in exists取反,错误,是不含空值null的取反
–常用统计函数
SELECT sex,sum(salary) as sumS, count(sex)as C
FROM Person
WHERE departId not in
( SELECT _departId FROM Department
WHERE departName LIKE ‘t%’)
group by sex;
–not in 不是in的取反吗,不是,不包括null
–group by查询中select的字段只能是group后所跟字段或函数字段(很好理解啊就是要得到整个组的特征而非个体特征
)
–count统计满足某条件的记录条数
–sum 统计某数值字段符合条件的记录的该字段数值和
–一次插入多条数据(格式一样?)
Insert into department values(1,’ec’),(2,’pro’),(3,’hr’);
–使用select语句插入
–注意不能为主键插入空值,另:!=某个值,is not null)
Insert into department(_departId)
select departId from Person
where departId is not null;
–插入非空且不存在于原表的数据
Insert into department(_departId)
select departId from Person
where departId is not null
and departId not in (select _departId from department);
–复制表
–(dept 未创建的新表,结构与数据一同复制)
SELECT * INTO dept FROM department;
–注意是否为空值的判断
update Person set departId=10 where departId is null;
–表连接后update
update Person set salary=10000 where departId=(select _departId from department where departName=’tech’);
–注意列名一定要写对,如果子查询列名不正确(_departId 错写为departId,所有记录都会被修改 )
–indetity
标识列, identity(a,b),a,b均为正整数,a表示开始数,b表示增幅,就像identity(1,1)意思就是该列自动增长,由
1开始每次增加是1
create table Department2
(_departId int identity(2,1),
departName varchar(20),
)
–identity(2,1),能否同时添加主键约束,可以,不用逗号,以空格分隔
–distinct 与unique
–定义列时添加唯一约束UNIQUE,查找时去重distinct,(约定俗成而已,distinct更标准,支持的库更多)
–distinct 可用于多列
select distinct name, id from A(组合去重)
–group by 也可用于多列
–select DepartCode,TypeId,Levels,Approval from v_Flow_Main_Flow_Step group by DepartCode,TypeId,Levels,Approval having count(*)>1
–union(两个来源的记录显示在同一列(创建一个新列名),去重)
select departName from dept
union
select departName from department
–union all(不去重)
select departName from dept
union all
select departName from department
–约束
–类型:非空约束 Not Null、主键约束primary key、唯一约束 UNIQUE、外键约束 foreign key (父子表)、校验约束check(校验字段 校验条件)、默认约束default(默认值)
–alter table emp add constraint emp_name_pk primary key(emp_name)
–alter table emp_pay add constraint emp_id_fk foreign key(emp_id) references emp(emp_id);
–add constraint chk_emp_age check(emp_age BETWEEN 15 AND 40)
–索引
–为了快速获取数据,避免全表扫描(但索引本身会占内存)
–create index id_cmpd_index on bills(account_id,amount);
–即使两个字段相结合,也只是建立了一个实际的索引
–主键和唯一约束都使系统自动生成隐性索引
–聚集索引与非聚集索引
–聚集,物理排列按索引所在字段顺序(所以一个表只能有一个聚集索引)
–非聚集,使用索引表(相当于书的目录)
–注意不要使用 %张% 以及 in or这类语句,这会使索引实效,(索引带来的range query时的便利会因为无法同时判断两个条件(where f1>100 or f2<50)而消失)
–范式
–第一范式,原子性,字段内容不可再分(是否不可再分要看情况,地址可以是一个字段,如果总是访问“城市”部分就要考虑把它拆出来)
–第二范式,所有字段都与主键相关(而非与主键的一部分相关(联合主键时)eg:主键为订单号与商品号时,商品信息字段不应该出现在表中,因为只依赖于商品号与订单号无关)
–第三范式,每一列数据都和主键直接相关,而不能间接相关。也可以理解为非主键列互不依赖,即可消除传递依赖
–事务
–四大特征:ACID原子性一致性隔离性持久性
–三类:自动提交事务,每条sql语句
–显示事务,begin transaction
–隐式事务,Set IMPLICIT_TRANSACTIONS ON