I am very new to SQL and am unable to understand this error: Violation of UNIQUE KEY constraint 'UQ__Flight_L__5DD08D7924EB8625'. Cannot insert duplicate key in object 'dbo.Flight_Leg'. The duplicate key value is (WN380)
Create Table Flight_Leg(
Leg_number int not null,
Departure_airport_code varchar(3),
Scheduled_departure_time varchar(6),
Arrival_airport_code varchar(3),
Scheduled_arrival_time varchar(6),
/*The maximum number of flight legs(Leg_number in the FLIGHT_LEG) cannot exceed 4*/
CHECK (Leg_number<=4),
Flight_number varchar(255) not null UNIQUE FOREIGN KEY REFERENCES Flight(Flight_number),
PRIMARY KEY (Leg_number,Flight_number),
);
INSERT INTO Flight_leg(Flight_number, Leg_number, Departure_airport_code, Scheduled_departure_time, Arrival_airport_code, Scheduled_arrival_time)
VALUES ('G4155', 1, 'SCK', '531PM', 'IWA', '814PM'),
('G4154', 1, 'IWA', '406PM', 'SCK', '451PM'),
('DL5841', 1, 'OAK', '1240PM', 'LAX', '200PM'),
('DL1149',1,'LAX','645PM', 'HNL', '1043PM'),
('HA48', 1, 'HNL', '215PM', 'OAK', '930PM'),
('AA1522', 1, 'SFO', '1159PM', 'ORD', '604AM'),
('AA3472', 1,'ORD', '719AM', 'MSN', '819AM'),
('WN380', 1,'MDW', '755AM', 'ONT', '1010AM'),
('WN380', 2, 'ONT', '1045AM', 'SMF', '1145AM'),
('B6624', 1, 'LAX', '915PM', 'JFK', '522AM');
In my head, I've made a composite key in flight_leg, so having duplicate values for WN380 should not produce this error? Thank you in advance!
CodePudding user response:
You have a uniqe constraint over Flight, which won't work
UNIQUE FOREIGN KEY REFERENCES Flight(Flight_number)
So, you can't insert two identical Flight_Legs, no matter what your primary index is
Make a normal NON-UNIQUE KEY REFERENCE and it will work:
Flight_number varchar(255) not null FOREIGN KEY REFERENCES Flight(Flight_number),
In your Flight Table, the Key can be UNIQE
best regards