/*-输出语句-*/ print convert(varchar(大小),变量或字符串) --只适合打印字符和字符串 select 变量 as 自定义列名 --适合所有类型 /*-逻辑控制语句-*/ --if-else条件语句 if(条件) begin --语句块 end else begin --语句块 end --while循环语句 while(条件) begin --语句块 end --case多分支语句 case when 条件1 then 结果1 when 条件2 then 结果2 else 结果3 end 列名 = case when 列值 then 表达式 else 表达式 end/*-高级查询-*/ --简单子查询 select 列名 from 表名 where 条件列名 = (select 条件列名 from 表名 where 条件) --in和not in子查询 select 列名 from 表名 where 条件列名 in (select 条件列名 from 表名 where 条件) select 列名 from 表名 where 条件列名 not in (select 条件列名 from 表名 where 条件) --exists和not exists子查询 if exists(select * from 表名 where 条件) begin --语句块 end if not exists(select * from 表名 where 条件) begin --语句块 end/*-事务-*/ --管理事务开始事务:begin transaction 提交事务:commit transaction 回滚事务:rollback transaction --分类 显示事务:用begin transaction 明确指定事务的开始 隐式事务:通过设置set implicit_transaction on 语句,将隐式事务模式设置为开. 当隐式事务模式操作时,SQL Server将在提交或回滚事务后自动启动新事务.无法描述事务 的开始,只需要提交或回滚每个事务. 自动提交事务:这是SQL Server 的默认模式,它将每条单独的T-SQL 语句视为一个事务. 如果成功执行,则自动提交.如果错误,则自动回滚. --开始事务 begin transaction --定义变量,用于累计错误 declare @errorSum int --初始化变量 set @errorSum=0 --语句 --累计错误 set @errorSum = @errorSum + @@error if @errorSum <>0 begin print --错误提示 --回滚事务 rollback transaction end else begin print --成功提示
--提交事务 commit transaction end
/*-索引-*/
--索引类型唯一索引:unique 聚集索引:clustered 非聚集索引:nonclusered
use 数据库名
go
--查找索引
if exists (select * from sysindexes where name = '索引名')
--删除索引
drop index 表名.索引名
--创建索引
create nonclustered index 索引名
on 表名(索引列名)
where fillfactor = --大小为0-100之间的值
go
--查询索引
select * from 表名 (index = 索引名) where 由索引列名组成的条件
/*-创建视图-*/
use 数据库名
go
--查询视图
if exists (select * from sysobjects where name = '视图名')
--删除视图
drop view 视图名
--创建视图
create view 视图名
as
--查询语句
go
--自定义存储过程
--不带参的存储过程
use 数据库名
go
--查询存储过程
if exists (select * from sysobjects where name = '存储过程')
--删除存储过程
drop procedure 存储过程名
go
--创建存储过程
create procedure 存储过程名
as
declare @变量名 数据类型
--SQL语句(一般用于查询语句)
go
--调用存储过程
exec 存储过程名
--创建带输入参数的存储过程
use 数据库名
go
--查询存储过程
if exists (select * from sysobjects where name = '存储过程')
--删除存储过程
drop procedure 存储过程名
go
--创建存储过程
create procedure 存储过程名
@变量名1 数据类型 --输入参数(当多个参数时用,隔开)
as
declare @变量名2 数据类型
--SQL语句(一般用于插入、修改、删除语句)
go
--调用存储过程
exec 存储过程名 给变量名1赋值
--创建带输出参数的存储过程
use 数据库名
go
--查询存储过程
if exists (select * from sysobjects where name = '存储过程')
--删除存储过程
drop procedure 存储过程名
go
--创建存储过程
create procedure 存储过程名
@变量名1 数据类型 output,--output关键字,否则视为输入参数
@变量名2 数据类型 --输入参数(当多个参数时用,隔开)
as
declare @变量名3 数据类型
--SQL语句(一般用于查询语句)
go
/*-处理错误信息-*/
use 数据库名
go
--查询存储过程
if exists (select * from sysobjects where name = '存储过程')
--删除存储过程
drop procedure 存储过程名
go
--创建存储过程
create procedure 存储过程名
@变量名1 数据类型,
@变量名2 output
as
declare @变量名3 数据类型
--错误处理
msg_id:在sysmessages系统表中指定的用户定义错误信息
msg_str:用户定义的特定信息,最长为255个字符
serverity:与特定信息相关联,表示用户定义的严重级别.用户可以使用0~18级,19~25级
是sysadmin固定角色的成员预留的,并且需要指定with log选项,20~25级错
误被认为是致命的错误
state:表示错误的状态,是1~127的值
raiserror('msg_id | msg_str',severity,state);
--SQL语句(一般用于查询语句)
go