2017-3-16 T-SQL基本编程 存储过程 触发器

1、 TSQL 基本编程:

定义变量:(注意:数据类型是sql server 里面的数据类型):

declare @(变量名)  int;

declare @a  nvarchar(200);

赋值:

set @a = '呵呵';

select  @a =max(degree) from score

select  @b='aaaaaa'

输出:

select @a  映射到结果集中

print  @a  打印到消息框

分支语句:

select @a = 2;

select @b =1;

if @a>@b

begin

   select 'a比b大'

end

else

begin

   select 'b比a大'

end

循环语句:

循环四要素:初始条件,循环条件,循环体,状态改变。

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

while  @aa<=10-----循环条件
begin
     select @aa;----循环体

   select @aa = @aa +1;----状态改变
end

2、存储过程:(相当于函数)

创建存储过程:

函数四要素: 输入,输出,函数名,函数体。

create  proc   jiafa -------创建存储过程名

@a  int,----参数

@b int,-----参数

as

return @a+@b;-----函数体

使用存储过程:

exec  存储过程名

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

例子:

create proc JiaFa
@a int,
@b int
as
return @a+@b;

declare @ccc int;

exec @ccc = JiaFa 25,10

select @ccc

------------------------------------------

create proc SelectAll
as
select *from Student
select *from Score
select *from Course
select *from teacher

exec SelectAll

3.触发器:

定义:一个特殊的存储过程,没办法直接调用它,而是通过增删改的动作来触发它
一个表的一个动作只能有一个触发器

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

例子:

create trigger users_Insert
on users
for insert
as
select *from users

--------------------------------------------

create trigger  Users_delete

on users

instead of  delete

as

select * from  users

--------------------------------------------------

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

级联删除:

create trigger  class_delete

on class

instead of  delete

as

declare  @a  nvarchar(200);

select  @a=classcode from deleted;

delete from users where class = @a;

delete from class where classcode = @a;

注:users  表里的  class 列约束 class 表里的 classcode 列 ,先删除users  表里的  class 列才可以删除 class 表里的 classcode 列 

转载于:https://www.cnblogs.com/zhengqian/p/6560540.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值