2014-01-29 98 views
1
create table Train_Types 
(
id int not null primary key, 
name varchar(50) not null 
) 

create table Trains 
(
id int not null primary key, 
name varchar(50) not null, 
trainTypeId int not null foreign key references Train_Types(id) 
) 

create table Stations 
(
id int not null primary key, 
name varchar(50) not null 
) 

create table Routs 
(
id int not null primary key, 
name varchar(50) not null, 
trainId int not null foreign key references Trains(id) 
) 

create table Routes_Stations 
(
stationId int not null foreign key references Stations(id), 
routeId int not null foreign key references Routs(id), 
arrivalDate datetime not null, 
departureDate datetime not null 
) 


create procedure addStation @stationId int, @routeId int, @arrivalTime datetime, 
          @departureTime datetime 
as 
begin 
insert into Routes_Stations (stationId,routeId,arrivalDate,departureDate) 
values (@stationId, @routeId, @arrivalTime, @departureTime) 
end 
go 

所以這裏我基本上有一個火車時刻表數據庫。我試圖制定一個程序來接收車站,路線,到達和出發時間,並將這個新車站添加到路線中。我的問題是,當我寫這篇文章程序不起作用

exec addStation 1,4,'18:00','18:05' 

我得到這個錯誤:

消息547,級別16,狀態0,過程addStation,5號線
INSERT語句衝突與外鍵約束「FK__Routes_St_ stati _1DE57479」。衝突發生在數據庫「火車時刻表」,表「dbo.Stations」,列'id'中。

我不明白它說什麼。有人可以幫我修復它請我是新來的數據庫

現在,我解決了我的問題,我嘗試修改此過程,以便如果我想要插入的站點已存在,我只需更新到達和出發時間。到目前爲止,我寫了這個,但我卡住了,我不知道如何分配總數。的站點變量。

create procedure addStation @stationId int, @routeId int, @arrivalTime datetime, 
          @departureTime datetime 
as 
begin 
declare @isStation_inRoute int 
set @isStation_inRoute = 0 

select *from Routes_Stations where stationId = @stationId 
and routeId = @routeId 
@isStation_inRoute = count(*) 
insert into Routes_Stations (stationId,routeId,arrivalDate,departureDate) 
values (@stationId, @routeId, @arrivalTime, @departureTime) 
end 
go 

回答

3

的錯誤說:你想插入行dbo.Routes_StationsStationId值在引用dbo.Stations父表不存在

看來你試圖插入一個stationId = 1值 - 並從錯誤判斷,StationId值不存在。

此行爲是外鍵約束的整點:不能插入與FK關係不匹配的數據。那些將是「幽靈記錄」,指向一個不存在的電臺的路線。您需要確保只將有效值插入到您的外鍵列中!

+0

哦,現在我明白了。我沒有在我的數據庫中插入任何東西 – user3043278