数据库
数据库
创建
create database database_name
删除
drop database database_name
修改
alter database database_name
ADD FILE (name = '',filename = 'path',size = ,maxsize = ,filegrowth = )
add log()
表
创建
create table tbname(col type [not null] [primary key],
col2 type [not null] ...)
删除
drop table tbname
由其他表创建新表
select colname into table1 from table2
修改表
alter table table1
ADD remark type
drop primary key(col)
插入
insert into table_name|view_name|... col_name values(),(),();
更新
update table_name set col_name = '' where ...
查询
投影查询
select select_list1,select_list2
from table_name
where ...
gruop by ...
having ...
order by ...
指定列
select col_name as '列名' from table_name where search_condition
全部列
select * from table_name where search_condition
去重
select distinct col_name from ...
条件查询
where ...
连接查询
(多表)等值连接
select tbname.col_name ,tbname2.col_name,tbname3.col_name
from tbname,tbname2,tbname3
where tbname.Ano = tbname.Ano2 and tbname2.Bno = tbname3.Bno
Join连接
select * from table_name1 join table_name2 on table_name1.Ano = table_name2.Ano
where search_condition
分组
eg:
select cno ,MAX(grade),MIN(grade),AVG(grade)
from score
where not grade IS null
group by cno
HAVING condtion
执行顺序:
where、group by、聚合函数、having
排序
select col_name
from table_name
where search_condition
order by col DESC 降序| ASC 升序
子查询
select a.col,
from tableA a
where bcol IN (
select bcol from b where bno =
)
select a.col,
from tableA a
where bcol > ALL | SOME | ANY (
select bcol from b where bno =
)
select a.col,
from tableA a
where exists(
select bcol from b where bno =
)
UNION
将多表合并成一个数据集
select a.col,
from tableA a
where exists(
select bcol from b where bno =
)
UNION
select a.col,
from tableA a
where bcol > ALL | SOME | ANY (
select bcol from b where bno =
)
EXCEPT INTERSECT 返回非重复值
EXCEPT 从左查询中返回有查询没查到的所有非重复值
INTERSECT 左右两边的两个查询都返回所有非重复值
TOP
接在select后表示 返回前几行数据
视图
创建
create view view_name
AS
select col from table_name where ...
WITH CHECK OPTION
查询\修改
和表一样
update view set conditon
where search_condition
删除
delete from view_name
where search_condition
索引
创建
create INDEX index_name on table_name(col_name)
create UNIQUE CLUSTERED INDEX index_name ON table_name(col_name)
查看
EXEC sp_helpindex tableName
重建
alter index index_name on table_name rebuild
with (PAD_INDEX = ON,FILEFACTOR = 80)
删除
drop index table_or_view_name.index_name
变量
局部变量&&全局变量
eg:
declare @spe char(12)
set @spe = '计算机'
select stno,stname,stsex
from student
where speciality = @spe
begin…end
IF…else等
if 条件
A
ELSE
B
变量需要先用declare定义出变量类型,
再用SET给变量赋值,
再用if while设置条件,
最后在begin-end中编写select语句
break
退出本层循环,当循环体中有多层循环嵌套时使用break只能退出其所在的层
continue
结束本次循环,重新转入循环开始条件的判断
goto语句
跳转到目标语句goto lp
return
无条件退出,之后的语句不被执行
waitfor
等到条件后执行
begin…end
IF…else等
if 条件
A
ELSE
B
变量需要先用declare定义出变量类型,
再用SET给变量赋值,
再用if while设置条件,
最后在begin-end中编写select语句
break
退出本层循环,当循环体中有多层循环嵌套时使用break只能退出其所在的层
continue
结束本次循环,重新转入循环开始条件的判断
goto语句
跳转到目标语句goto lp
return
无条件退出,之后的语句不被执行
waitfor
等到条件后执行
|