【问题标题】:How to do insert into table in if and else condition of triggers in SQL Server如何在 SQL Server 中触发器的 if 和 else 条件下插入表
【发布时间】:2018-12-29 20:25:40
【问题描述】:
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

【问题讨论】:

  • 和普通插入一样。没有魔法
  • Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已替换为 ANSI 中的 proper ANSI JOIN 语法-92 SQL 标准(25 多年前),不鼓励使用。
  • 触发器也可以影响多行,这里假设只有一个。并且您为 DELETE 和 INSERT 声明它,但在删除情况下 INSERTED 表将为空
  • 看起来你需要一个外键而不是触发器

标签: sql-server triggers


【解决方案1】:

就像 Martin Smith 在 cmets 部分中建议的那样,您确实需要在两个表之间进行外键约束。但是,处理这个问题的触发器看起来像......

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

【讨论】:

  • 还有一件事,兄弟..在其他部分插入的语法..??像 .. 通用插入
  • @ZarrarNiazi 是的。
猜你喜欢
  • 1970-01-01
  • 2012-12-11
  • 2021-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
  • 2013-11-09
相关资源
最近更新 更多