觸發器現有字典表(Dict)欄位說明Id標示ItemKey鍵ItemValue值UpperId上層標示需求一:當新增一條記錄的時候,若已存在相同鍵的,拒絕插入//操作步驟:展開相關表,右擊‘觸發器’,新建即可USE [sqlffwj]GOSET ANSI_NULLS ONGOSET QUOTED_I...
觸發器
現有字典表(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()); }