如何制作一个sql限制

时间:2017-03-10 10:15:30

标签: mysql sql-server

我正在制作一个数据库系统,我想对可用的座位数量进行最大限制。每部电影应该只有100个座位。我该怎么办?

create table customer 
(p_No int not null,
name varchar (30),
lastname varchar (30),
constraint p_No_pk primary key(p_No))

create table movie
(title varchar (500),  
movie_No int not null,
seats int check(seats < 100),
date datetime, 
primary key(movie_No))

create table ticket 
(ticket_No int identity (1,1) not null,
movie_No int not null,
p_No int not null,
primary key(ticket_No),
foreign key(movie_No)
references movie (movie_No),
foreign key(p_No) 
references customer(p_No))

2 个答案:

答案 0 :(得分:2)

创建检查约束,如下所示.... SQL SERVER

create table movie
(title varchar (500),  
movie_No int not null,
seats int ,
date datetime, 
primary key(movie_No)
CONSTRAINT CHK_seats   
   CHECK (seats <100))

答案 1 :(得分:1)

使用CHECK约束。 E.g:

CREATE TABLE t1 (x TINYINT NOT NULL UNIQUE CHECK (x BETWEEN 1 AND 100));

或者你可以在桌面上创建一个AFTER INSERT触发器。

create trigger LimitTable
on YourTableToLimit
after insert
as
declare @tableCount int
select @tableCount = Count(*)
from YourTableToLimit

if @tableCount > 100
begin
    rollback
end
go