触发器和存储过程
触发器
现有字典表(Dict)
字段 | 说明 |
Id | 标示 |
ItemKey | 键 |
ItemValue | 值 |
UpperId | 上层标示 |
需求一:当新增一条记录的时候,若已存在相同键的,拒绝插入
//操作步骤:展开相关表,右击‘触发器’,新建即可
USE [sqlffwj] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TRIGGER [dbo].[CheckKeyRepeated] ON [dbo].[Dict] for INSERT AS if(select COUNT(*) from [Dict], inserted inobj where [Dict].ItemKey = inobj.ItemKey and [Dict].Id != inobj.Id) > 0 BEGIN raiserror('已有相同键,不能插入',16,1) rollback tran END
需求二:当删除一条记录的时候,若有下层记录,拒绝删除
USE [sqlffwj] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TRIGGER [dbo].[CheckDependence] ON [dbo].[Dict] for delete AS if(select COUNT(*) from [Dict], deleted delbj where [Dict].UpperId = delbj.Id) > 0 BEGIN raiserror('有下层记录,不能删除',16,1) rollback tran END
需求三:当删除一条记录的时候,若有下层记录,下层也一起删除
USE [sqlffwj] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TRIGGER [dbo].[CheckDependence2] ON [dbo].[Dict] AFTER delete AS while(select COUNT(*) from [Dict] where UpperId != 0 and UpperId not in (select Id from [Dict])) > 0 BEGIN delete from [Dict] where UpperId != 0 and UpperId not in (select Id from [Dict]) END
存储过程
现有用户表(User)
字段 | 说明 |
Id | 标示 |
Name | 姓名 |
Age | 年龄 |
DeptId | 部门标示 |
部门表(Dept)
字段 | 说明 |
Id | 标示 |
Name | 名称 |
需求一:用存储过程查询所有用户的信息(标示、姓名、年龄、部门名)
//操作步骤:展开数据库,再展开可编程性,右击‘存储过程’,新建即可
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[GetUsers] AS BEGIN select [User].Id '标示',[User].Name '姓名', [User].Age '年龄', [Dept].Name '部门' from [User] left join [Dept] on [User].DeptId = [Dept].Id END GO
/* 调用 */ exec GetUsers
需求二:用存储过程查询指定部门的用户信息(标示、姓名、年龄、部门名)
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[GetUsersByDept] ( @deptid int /* 部门标示 */ ) AS BEGIN select [User].Id '标示',[User].Name '姓名', [User].Age '年龄', [Dept].Name '部门' from [User] left join [Dept] on [User].DeptId = [Dept].Id where [Dept].Id = @deptid END GO
/* 调用 */ exec GetUsersByDept 2
需求三:在项目中用ADO调用存储过程'GetUsersByDept'
1、环境:VS2010+sql2008
2、新建edmx文件,引用两张表和存储过程
3、切换到‘模型浏览器’,‘添加函数导入’
4、在‘添加函数导入’面板,点击‘获取列信息’,获取到列信息后再点击‘创建新的复杂类型’,确定后就可以通过Func调用存储过程了
5、调用代码Demo
using (var context = new SqltestEntities()) { var result = context.GetUsersByDept(2); throw new Exception(result.Count().ToString()); }