我是 SQL 新手,我有一个任务,需要创建一个过程来获取客户 ID 和日历 ID,并在未达到座位限制时将预订插入预订表。我知道这是非常基本的,但无论如何我希望它没问题。 我一整天都在尝试谷歌搜索,当我认为我找到了一些东西时,它对我不起作用,因为我无法正确应用它。
表格看起来像这样:
Customer
(
ID INT IDENTITY(1,1) PRIMARY KEY,
Firstname VARCHAR(15) NOT NULL,
Lastname VARCHAR(20) NOT NULL,
Email VARCHAR(50),
Phonenumber CHAR(12),
)
Calendar
(
ID INT IDENTITY(1,1) PRIMARY KEY,
Departure SMALLDATETIME NOT NULL,
Arrival SMALLDATETIME NOT NULL,
Departing_from VARCHAR(10) NOT NULL,
Arriving_to VARCHAR(10) NOT NULL,
Seats INT NOT NULL
)
Booking
(
ID INT IDENTITY(1,1) PRIMARY KEY,
Booking_date SMALLDATETIME NOT NULL,
Cu_ID INT FOREIGN KEY REFERENCES Customer(ID),
Ca_ID INT FOREIGN KEY REFERENCES Calendar(ID)
)
我尝试了这个过程,但出现语法错误
CREATE PROCEDURE booking_proc1
AS
DECLARE @Booked_Seats INT
DECLARE @smalldatetime smalldatetime
SET @Booked_Seats = 0
BEGIN
INSERT INTO Booking
SELECT
CASE
WHEN @Booked_Seats < 5
THEN (@smalldatetime, ID FROM Customer
WHERE ID = 1,
ID FROM Calendar WHERE ID = 1)
ELSE 'Flight is full'
END;
exec booking_proc1
试试这个:
/*
Example:
Seats Limit = 20
Bookin Date = '06/15/2021'
CustomerID = 1
CalendarID = 55
Call it like this:
EXEC dbo.usp_Booking_Insert 20 '06/15/2021', 1, 55
*/
CREATE PROCEDURE dbo.usp_Booking_Insert
@SeatsLimit int
, @BookingDate datetime
, @CustomerID int
, @CalendarID int
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SeatsBooked int = (SELECT SUM(Seats) FROM @Calendar WHERE ID = @CalendarID)
IF @SeatsLimit > @SeatsBooked
BEGIN
INSERT INTO @Booking VALUES (@BookingDate, @CustomerID, @CalendarID);
END
;
END
GO
客户 ( ID INT 身份(1,1) 主键, 名字 VARCHAR(15) NOT NULL, 姓氏 VARCHAR(20) NOT NULL, 电子邮件 VARCHAR(50), 电话号码 CHAR(12), )
日历 ( ID INT IDENTITY(1,1) 主键, 出发时间 SMALLDATETIME NOT NULL, 到达 SMALLDATETIME NOT NULL, Departing_from VARCHAR(10) NOT NULL, Arriving_to VARCHAR(10) NOT NULL, 座位 INT NOT NULL )
预订
(
ID INT IDENTITY(1,1) 主键,
Booking_date SMALLDATETIME NOT NULL,
Cu_ID INT 外键参考客户(ID),
Ca_ID INT 外键引用 日历 (ID)
)