用SQL语句实现部门、职务、职称等基本信息的管理; 实现教职工信息的管理; 实现工资项目的管理,工资项目设有启用标志和加扣标志; 实现教职工工资项目及其工资的管理; 创建触发器当往教职工工资项目表中插入记录或删除记录时,自动修改该职工的应发工资数和实发工资数; 创建存储过程统计某个月各种工资项目的发放总和; 创建视图查询各个员工的应发、应扣和实发工资; 建立数据库相关表之间的参照完整性约束。
时间: 2024-02-16 08:00:00 浏览: 132
这是一个相对复杂的数据库管理系统,需要设计多个表并建立它们之间的关联关系,以下是一些基本的SQL语句示例:
1. 创建部门、职务、职称等基本信息表
```
CREATE TABLE department (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50) NOT NULL
);
CREATE TABLE position (
pos_id INT PRIMARY KEY,
pos_name VARCHAR(50) NOT NULL
);
CREATE TABLE title (
title_id INT PRIMARY KEY,
title_name VARCHAR(50) NOT NULL
);
```
2. 创建教职工信息表
```
CREATE TABLE employee (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50) NOT NULL,
emp_dept_id INT NOT NULL,
emp_pos_id INT NOT NULL,
emp_title_id INT NOT NULL,
emp_salary DECIMAL(10, 2) DEFAULT 0.00,
FOREIGN KEY (emp_dept_id) REFERENCES department(dept_id),
FOREIGN KEY (emp_pos_id) REFERENCES position(pos_id),
FOREIGN KEY (emp_title_id) REFERENCES title(title_id)
);
```
3. 创建工资项目表
```
CREATE TABLE salary_item (
item_id INT PRIMARY KEY,
item_name VARCHAR(50) NOT NULL,
is_enabled BOOLEAN DEFAULT TRUE,
is_deduction BOOLEAN DEFAULT FALSE
);
```
4. 创建教职工工资项目表
```
CREATE TABLE emp_salary_item (
emp_id INT NOT NULL,
item_id INT NOT NULL,
salary DECIMAL(10, 2) DEFAULT 0.00,
FOREIGN KEY (emp_id) REFERENCES employee(emp_id),
FOREIGN KEY (item_id) REFERENCES salary_item(item_id)
);
```
5. 创建触发器,自动修改教职工的应发工资和实发工资
```
CREATE TRIGGER update_salary
AFTER INSERT OR DELETE ON emp_salary_item
FOR EACH ROW
BEGIN
UPDATE employee SET emp_salary = (
SELECT SUM(salary) FROM emp_salary_item WHERE emp_id = NEW.emp_id AND is_deduction = 0
) WHERE emp_id = NEW.emp_id;
UPDATE employee SET emp_salary = emp_salary - (
SELECT SUM(salary) FROM emp_salary_item WHERE emp_id = NEW.emp_id AND is_deduction = 1
) WHERE emp_id = NEW.emp_id;
END;
```
6. 创建存储过程,统计某个月各种工资项目的发放总和
```
CREATE PROCEDURE get_monthly_salary(IN month INT, OUT total_salary DECIMAL(10, 2))
BEGIN
SELECT SUM(salary) INTO total_salary FROM emp_salary_item WHERE MONTH(created_at) = month;
END;
```
7. 创建视图,查询各个员工的应发、应扣和实发工资
```
CREATE VIEW emp_salary AS
SELECT emp_id, emp_name, emp_dept_id, emp_pos_id, emp_title_id,
SUM(CASE WHEN is_deduction = 0 THEN salary ELSE 0 END) AS total_salary,
SUM(CASE WHEN is_deduction = 1 THEN salary ELSE 0 END) AS total_deduction,
emp_salary AS total_paid
FROM emp_salary_item
JOIN employee ON emp_salary_item.emp_id = employee.emp_id
GROUP BY emp_id;
```
8. 建立参照完整性约束
```
ALTER TABLE employee ADD CONSTRAINT fk_emp_dept FOREIGN KEY (emp_dept_id) REFERENCES department(dept_id);
ALTER TABLE employee ADD CONSTRAINT fk_emp_pos FOREIGN KEY (emp_pos_id) REFERENCES position(pos_id);
ALTER TABLE employee ADD CONSTRAINT fk_emp_title FOREIGN KEY (emp_title_id) REFERENCES title(title_id);
ALTER TABLE emp_salary_item ADD CONSTRAINT fk_emp_salary_item_emp FOREIGN KEY (emp_id) REFERENCES employee(emp_id);
ALTER TABLE emp_salary_item ADD CONSTRAINT fk_emp_salary_item_item FOREIGN KEY (item_id) REFERENCES salary_item(item_id);
```
阅读全文