创建存储过程
create procedure 存储过程名 @参数名1 数据类型1 [=default] [out | output | readonly]
as
...sql语句...
go
执行存储过程
execute 存储过程名 参数1
删除存储过程名
drop procedure 存储过程名
修改存储过程
alter procedure 存储过程名 @参数名1 数据类型1 [=default] [out | output | readonly]
as
...sql语句...
go
l 索引
创建索引
create [unique] [clustered | nonclustered] index 索引名
on 表名 (列名[,列名]...) [with fillfactor = x]
其中:
unique 表示将要创建唯一索引,唯一索引不允许两行具有相同的索引值
clustered表示将要创建聚集索引 或 nonclustered 表示将要创建非聚集
聚集索引在速度上比非聚集索引快,因为聚集索引中行的物理顺序与索引键值的逻辑顺序是一致的,但一个表中最多只能有一个聚集索引,可以有一个或多个非聚集索引
with fillfactor = x:表示填充因子,取值在0~100间的值,该值表示索引页填满的空间所占用的百分比,指定合适的填充因子可以提高数据改动时的执行效率
删除索引
drop index 索引名
常用的有:if exists (select * from sysindexes where name = 索引名) drop index 索引名
l 变量的使用
定义变量:
declare 变量名(必须以@开头) 数据类型
给变量赋值:
set 变量名 = 表达式
select 变量名=表达式 from 表或视图 ...
一般来说,简单赋值(比如赋给此变量一个常量)使用set,复杂的赋值(比如需要在表或视图中查询数据时)使用select
3个常用的全局变量:
@@error 最后一个T-SQL错误的错误号
@@identity 最后一次作插入操作时的标识列的值
@@rowcount 受上一个SQL语句影响的行数
l case多分支语句
case when 条件1 then 结果1
when 条件2 then 结果2
[else 其它结果]
end
l 子查询
select * from 表1 where 列1 { = | <> | != | > | >= | !> | < | <= | !< } [all | some | any](子查询)
some与any是等效的,相当于当前列1 的值与子查询的所有结果进行比较满足条件的至少有一个,相当于||运算
all与以上的相反,相当于&&运算
l 表联接查询
内联接:
select * from 表1 inner join 表2 on 条件
左外联:
select * from 表1 left outer join 表2 on 条件
右外联:
select * from 表1 right outer join 表2 on 条件
完全外联:
select * from 表1 full outer join 表2 on 条件
自联接:
select * from 表1 别名1 [inner | left outer | right outer | full outer] join 表1 别名2 on 条件(使用别名1和别名2)