试图找出当客人数量超过座位数时触发器允许将行插入座位表的原因。这是一个单行级触发器,我正在试验并在SO的帮助下进行自学。
create table dining_table
(
table_id int not null,
area_id int not null,
table_seats int not null
constraint PK_dining_table primary key(table_id),
constraint FK_dining_table_table_area foreign key(area_id)
references table_area(area_id)
);
insert into dining_table(table_id, area_id, table_seats)
values(1, 1, 2);
insert into dining_table(table_id, area_id, table_seats)
values(2, 2, 4);
create table customers
(
customer_id int not nulL,
cust_lastname varchar(50) not null,
cust_total_guests int not null,
constraint PK_customers primary key(customer_id)
);
insert into customers(customer_id, cust_lastname, cust_total_guests)
values(1, 'Wallman', 4);
insert into customers(customer_id, cust_lastname, cust_total_guests)
values(2, 'Griffin', 6);
create table seating
(
customer_id int not null,
table_id int not null,
seat_cost decimal(10,2) not null,
seat_date datetime not null,
tip_amount decimal(10,2) not null,
constraint PK_seating primary key(customer_id, table_id)
);
insert into seating(customer_id, table_id, seat_cost, seat_date,
tip_amount)
values(1, 1, 15.00, '20170506', 5.00);
insert into seating(customer_id, table_id, seat_cost, seat_date,
tip_amount)
values(2, 2, 35.50, '20170608', 11.00);
触发:
if OBJECT_ID('seats_available','U') is not null
drop trigger seats_available;
go
create trigger seats_available
on dbo.seating
instead of insert
as
begin
insert into seating
select *
from inserted
where exists (select dt.table_seats
from dining_table dt
join seating s on dt.table_id = s.table_id
join customers c on s.customer_id = c.customer_id
where dt.table_seats >= c.cust_total_guests)
end
go
--test trigger
insert into seating(customer_id, table_id, seat_cost, seat_date,
tip_amount)
values(2, 1, 25.00, GETDATE(), 3.00);
values(2, 2, 35.50, '20170608', 11.00);