我的预约表为[student].[dbo].[reservation]里面有预约号,座位号,学号,日期,预约开始时间,预计结束时间,实际开始时间,实际结束时间,签到状态。黑名单里有学号,日期。我想做一个sqlserver的触发器,当在预约表里,迟到,早退,晚到,不到,超过三次,就在黑名单里加入那个人的学号,日期,
时间: 2023-11-22 20:05:30 浏览: 96
sqlserver的触发器
好的,根据您的需求,可以编写如下的 SQL Server 触发器代码:
```
CREATE TRIGGER [dbo].[reservation_trigger]
ON [student].[dbo].[reservation]
AFTER UPDATE
AS
BEGIN
IF UPDATE(sign_in_status) -- 只有签到状态改变时才触发触发器
BEGIN
DECLARE @student_id INT
DECLARE @date DATE
DECLARE @late_count INT
DECLARE @early_leave_count INT
DECLARE @absent_count INT
SELECT @student_id = inserted.student_id, @date = inserted.date FROM inserted
-- 统计该学生在该日期内的迟到次数、早退次数、缺席次数
SELECT @late_count = COUNT(*) FROM [student].[dbo].[reservation] WHERE student_id = @student_id AND date = @date AND sign_in_status = 'late'
SELECT @early_leave_count = COUNT(*) FROM [student].[dbo].[reservation] WHERE student_id = @student_id AND date = @date AND sign_in_status = 'early leave'
SELECT @absent_count = COUNT(*) FROM [student].[dbo].[reservation] WHERE student_id = @student_id AND date = @date AND sign_in_status = 'absent'
-- 判断是否超过三次,如果是,则在黑名单表中插入该学生的学号和日期
IF @late_count + @early_leave_count + @absent_count > 3
BEGIN
INSERT INTO [student].[dbo].[blacklist] (student_id, date) VALUES (@student_id, @date)
END
END
END
```
触发器会在每次更新 `reservation` 表时触发,如果更新的字段是签到状态 `sign_in_status`,则会统计该学生在该日期内的迟到次数、早退次数、缺席次数,判断是否超过三次,如果是,则在黑名单表中插入该学生的学号和日期。
阅读全文