employee的字段有emp_id、name、gender、tel、id、job_id、job_lvl、hire_date; job表中的字段有job_id、job_desc、min_lvl、max_lvl; employee_log表中的字段有emp_id、name、gender、tel、id、job_id、job_lvl、hire_date、quit_date;使用SQL SERVER语言,编写一个触发器,保证employee表中的job_lvl的值在jobs表的相应记录的min_lvl和max_lvl范围内。并验证
时间: 2023-06-26 08:09:16 浏览: 82
emp.zip_eclipse+emp_emp.jar_java EMP_javaweb_jdbc
以下是触发器的代码:
```sql
CREATE TRIGGER tr_employee_job_lvl
ON employee
AFTER INSERT, UPDATE
AS
BEGIN
IF EXISTS (
SELECT 1
FROM inserted i
INNER JOIN jobs j ON i.job_id = j.job_id
WHERE i.job_lvl < j.min_lvl OR i.job_lvl > j.max_lvl
)
BEGIN
RAISERROR('Job level is not within the acceptable range', 16, 1)
ROLLBACK TRANSACTION
RETURN
END
END
```
这个触发器会在employee表发生插入或更新操作时触发。它会对插入或更新的记录进行检查,如果job_lvl的值不在jobs表中相应记录的min_lvl和max_lvl范围内,就会抛出错误并回滚事务。
为了验证这个触发器是否正常工作,我们可以进行以下测试:
首先,创建jobs表并插入一些数据:
```sql
CREATE TABLE jobs (
job_id INT PRIMARY KEY,
job_desc VARCHAR(50),
min_lvl INT,
max_lvl INT
)
INSERT INTO jobs VALUES (1, 'Manager', 1, 10)
INSERT INTO jobs VALUES (2, 'Engineer', 5, 15)
```
然后,创建employee表和employee_log表,并将触发器添加到employee表:
```sql
CREATE TABLE employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
gender CHAR(1),
tel VARCHAR(20),
id VARCHAR(20),
job_id INT,
job_lvl INT,
hire_date DATE
)
CREATE TABLE employee_log (
emp_id INT,
name VARCHAR(50),
gender CHAR(1),
tel VARCHAR(20),
id VARCHAR(20),
job_id INT,
job_lvl INT,
hire_date DATE,
quit_date DATE
)
CREATE TRIGGER tr_employee_job_lvl
ON employee
AFTER INSERT, UPDATE
AS
BEGIN
IF EXISTS (
SELECT 1
FROM inserted i
INNER JOIN jobs j ON i.job_id = j.job_id
WHERE i.job_lvl < j.min_lvl OR i.job_lvl > j.max_lvl
)
BEGIN
RAISERROR('Job level is not within the acceptable range', 16, 1)
ROLLBACK TRANSACTION
RETURN
END
END
```
接下来,尝试插入一个job_lvl不在范围内的记录,触发器应该会抛出错误并回滚事务:
```sql
INSERT INTO employee VALUES (1, 'John', 'M', '123456', 'ABC123', 1, 20, '2021-01-01')
-- Output: Msg 50000, Level 16, State 1, Procedure tr_employee_job_lvl, Line 11
-- Job level is not within the acceptable range
```
再尝试插入一个job_lvl在范围内的记录,应该会成功插入:
```sql
INSERT INTO employee VALUES (2, 'Jane', 'F', '789012', 'DEF456', 2, 10, '2021-02-01')
-- Output: (1 row affected)
```
最后,检查employee表和employee_log表,应该可以看到新插入的记录已经成功添加到employee表中,而employee_log表中没有记录:
```sql
SELECT * FROM employee
-- Output:
-- emp_id name gender tel id job_id job_lvl hire_date
-- 2 Jane F 789012 DEF456 2 10 2021-02-01
SELECT * FROM employee_log
-- Output: (0 rows)
```
阅读全文