sql-server - 如何在 SQL Server 中触发器的 if 和 else 条件下插入表
问题描述
create trigger thequery4
on employees
instead of insert, delete
as
declare @var3 int
select @var3 = d.D_ID
from inserted d, DEPARTMENTS dp
where d.D_ID = dp.D_ID
if (@var3 is null)
begin
print 'you are NOT allowed , B/C IS Its d_Id is not present in department '
end
else
begin
---- insert ----
end
解决方案
就像 Martin Smith 在评论部分中建议的那样,您确实需要两个表之间的外键约束。但是,处理此问题的触发器看起来像......
CREATE TRIGGER thequery4
ON employees
INSTEAD OF INSERT, DELETE
AS
BEGIN
IF EXISTS ( SELECT 1 FROM inserted i
WHERE NOT EXISTS ( SELECT 1
FROM DEPARTMENTS dp WHERE i.D_ID = dp.D_ID))
BEGIN
PRINT 'you are NOT allowed , B/C IS Its d_Id is not present in department '
END
ELSE
BEGIN
---- insert ----
END
END
推荐阅读
- c# - 计算除空白之外的唯一符号
- javascript - Microsoft 语音服务 Javascript SDK 超时
- java - 泽西客户端的测试用例失败
- javascript - 我不知道如何从 DOM (JavaScritp) 中获取数字
- svg - 在 svg 中转换 svg
- javascript - Asp.net MVC 5 视图在使用 F5 重新加载页面之前不呈现
- html - boostrap - 等于列高度 && 等于嵌套列内的行高度
- c# - 如何在 WPF 弹出窗口中显示 Gif?
- python - 如何从 XML int Python 中获得一些价值?
- python-2.7 - python 2.7 - 在 utf8 中编码操作系统