转载:SqlServer 编程基本语法 - lipan
# 一、定义变量
1 | --简单赋值 |
# 二、表、临时表、表变量
1 | --创建临时表1 |
1 | --创建临时表 |
1 | --给查询结果集增加自增长列 |
1 | --定义表变量 |
# 三、循环
1 | --while循环计算1到100的和 |
# 四、条件语句
1 | --if,else条件分支 |
# 五、游标
1 | declare @ID int |
# 六、触发器
触发器中的临时表:
Inserted
存放进行 insert 和 update 操作后的数据
Deleted
存放进行 delete 和 update 操作前的数据
1 | --创建触发器 |
# 七、存储过程
1 | --创建带output参数的存储过程 |
# 八、自定义函数
函数的分类:
1)标量值函数
2)表值函数
a: 内联表值函数
b: 多语句表值函数
3)系统函数
1 | --新建标量值函数 |
# 自定义函数与存储过程的区别
一、自定义函数:
-
可以返回表变量
-
限制颇多,包括
不能使用 output 参数;
不能用临时表;
函数内部的操作不能影响到外部环境;
不能通过 select 返回结果集;
不能 update,delete,数据库表;
-
必须 return 一个标量值或表变量
自定义函数一般用在复用度高,功能简单单一,争对性强的地方。
二、存储过程
-
不能返回表变量
-
限制少,可以执行对数据库表的操作,可以返回数据集
-
可以 return 一个标量值,也可以省略 return
存储过程一般用在实现复杂的功能,数据操纵方面。