【2017-03-16】TSQL基本编程、存储过程、触发器

一、TSQL基本编程

1、定义变量

declare @变量名 数据类型

2、赋值

set @变量名=值

select @变量名=值

3、取值(打印/映射)

select @变量名    --映射到结果集

print @变量名     --映射到消息框

4、分支语句

select @a = 2;

select @b =1;

if @a>@b

begin

   select 'a比b大'

end

else

begin

   select 'b比a大'

end

5、循环语句

declare @a int;
select @a = 1;    --初始条件

while  @a<=10   --循环条件

begin

     select @a;              --循环体

     select @a=@a+1;   --状态改变

end

二、存储过程

将代码放入存储过程中,可以快速调用这些代码,相当于C#中的函数

1、创建存储过程

create proc 存储过程名

@a int    --参数

@b int    --参数

as

  return @a+@b

2、调用存储过程

exec  存储过程名

exec  @a= 存储过程名  参数,参数

3、存储过程常用用法:

将查看表的代码放在存储过程中,在使用的时候只需调用存储过程exec Select_All 就可

create proc Select_All

as

select * from Student

select * from Score

select * from Course

select * from Teacher

exec Select_All

三、触发器

一个特殊的存储过程,没办法直接调用它,而是通过增删改查的动作来触发它。

一个表的一个动作只能有一个触发器。

create trigger 哪个表的哪个动作       --创建一个触发器+ 名字
on 表名                                       --针对于哪一个表写的触发器     
for 动作 / instead of 动作               --针对于哪一个动作触发之后的触发器  /   --针对于哪一个动作执行替换
as 
触发器内容

例:

create trigger  Users_delete

on users

instead of  delete

as

declare  @a  nvarchar(200);

select  @a=ids from deleted;

if @a=5

begin

     select'抱歉,不能删除此项!'

end

else

begin

    delete  from users  where ids=@a

end

delete   from  users  wheres  ids=5

 触发器常用用法——级联删除

要删除class表中的classcode列,classcode为被约束列,需通过触发器来实现。先把外键表users中对应的class列数据删除,再把主键表class中的classcode数据删除。

 

原文地址:https://www.cnblogs.com/snow22546/p/6566611.html