SQL Server级联更新如何实现,是很多人都提到过的问题,下面就教您SQL Server级联更新和级联插入的方法,希望可以让您对SQL Server级联更新有更深的认识。
--INSERT 数据插入,验证外键关联逻辑,错误抛出出错信息
- IF EXISTS (SELECT NAME FROM SYSOBJECTS
- WHERE NAME = 'INS_DOCUMENTTYPE_001' AND TYPE = 'TR')
- DROP TRIGGER INS_DOCUMENTTYPE_001
- GO
- CREATE TRIGGER INS_DOCUMENTTYPE_001
- ON dbo.DOCUMENTTYPE
- FOR INSERT
- AS
- IF (SELECT COUNT(*) FROM INSERTED WHERE UPNO IS NOT NULL
- AND (UPNO = NO OR UPNO NOT IN (SELECT NO FROM dbo.DOCUMENTTYPE))) > 0
- BEGIN
- DELETE FROM dbo.DOCUMENTTYPE WHERE NO IN (SELECT NO FROM INSERTED)
- RAISERROR('在被引用表 dbo.DOCUMENTTYPE 中没有与外键 UPNO 的引用列的列表匹配的主键或候选键。',16,1)
- END
- GO
--UPDATE 数据更新,如果更新了外键,验证外键存在
- IF EXISTS (SELECT NAME FROM SYSOBJECTS
- WHERE NAME = 'UPD_DOCUMENTTYPE_001' AND TYPE = 'TR')
- DROP TRIGGER UPD_DOCUMENTTYPE_001
- GO
- CREATE TRIGGER UPD_DOCUMENTTYPE_001
- ON dbo.DOCUMENTTYPE
- FOR UPDATE
- AS
- IF (SELECT COUNT(*) FROM INSERTED WHERE UPNO IS NOT NULL
- AND (UPNO = NO OR UPNO NOT IN (SELECT NO FROM dbo.DOCUMENTTYPE))) > 0
- BEGIN
- SET IDENTITY_INSERT dbo.DOCUMENTTYPE ON
- DELETE FROM dbo.DOCUMENTTYPE WHERE NO IN (SELECT NO FROM INSERTED)
- -- INSERT INTO dbo.DOCUMENTTYPE SELECT * FROM INSERTED
- SELECT * INTO dbo.DOCUMENTTYPE FROM INSERTED
- SET IDENTITY_INSERT dbo.DOCUMENTTYPE OFF
- RAISERROR('在被引用表 dbo.DOCUMENTTYPE 中没有与外键 UPNO 的引用列的列表匹配的主键或候选键。',16,1)
- END
- GO
当前名称:SQLServer级联更新的实现
当前地址:http://www.shufengxianlan.com/qtweb/news28/338028.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联