在触发器中实现条件

时间:2014-11-05 21:44:38

标签: sql sql-server

因此,我正在使用的环境是MS SQL Server Management Studio,并证明它对触发器非常痛苦。我尝试做的是创建一个触发器,如果​​新员工的工资低于他们所在部门的所有其他员工,则会在新表(SALARY_VIOLATION_NEW_EMP)中插入新员工的信息。

我有它在新表中插入新信息的地方,我只是无法弄清楚如何实现这个条件。这就是我到目前为止所做的:

CREATE TRIGGER SALARY_VIOLATION
ON  EMPLOYEE 
AFTER INSERT
AS 
BEGIN

declare @newFname varchar(50), @newLname varchar(50), @newSsn char(9), @newSex char(1),
        @newSalary decimal(10,2), @newSuper_ssn char(9), @newDno int;

select @newFname = Fname,
       @newLname = Lname,
       @newSsn = Ssn,
       @newSex = Sex,
       @newSalary = Salary,
       @newSuper_ssn = Super_ssn,
       @newDno = Dno from inserted;

INSERT INTO SALARY_VIOLATION_NEW_EMP(FirstName,LastName,Ssn,Sex,Salary,Super_ssn,Dno)
    values(@newFname, @newLname, @newSsn, @newSex, @newSalary, @newSuper_ssn, @newDno);

END
GO

为了节省一些时间,我有满足两个表格的测试数据:

insert into EMPLOYEE values ('John',null,'doe','234536779',null,null,'M', 20000,'987654321',4)

2 个答案:

答案 0 :(得分:1)

当你不填充变量时,使用触发器会更有趣,而是采用基于集合的方法。

INSERT INTO MyNewTable (ColumnList)
SELECT ColumnList
FROM Inserted
WHERE SomeCondition=true

答案 1 :(得分:0)

如果Dno是您的部门编号,那么:

 CREATE TRIGGER SALARY_VIOLATION
 ON  EMPLOYEE 
 AFTER INSERT
 AS 
 BEGIN

 declare @newFname varchar(50), @newLname varchar(50), @newSsn char(9), @newSex char(1),
    @newSalary decimal(10,2), @newSuper_ssn char(9), @newDno int;

 select @newFname = Fname,
   @newLname = Lname,
   @newSsn = Ssn,
   @newSex = Sex,
   @newSalary = Salary,
   @newSuper_ssn = Super_ssn,
   @newDno = Dno from inserted;

 declare @MinSalary decimal(10,2)
 select @MinSalary = min(Salary) from [EMPLOYEE] where Dno = @newDno and Ssn != @newSsn

 if @MinSalary > @newSalary
 begin

 INSERT INTO SALARY_VIOLATION_NEW_EMP(FirstName,LastName,Ssn,Sex,Salary,Super_ssn,Dno)
     values(@newFname, @newLname, @newSsn, @newSex, @newSalary, @newSuper_ssn, @newDno);
 end;

 END

GO