无法在SQL Server中为同一主键插入2个外键的数据

时间:2018-11-19 18:34:26

标签: sql-server

我无法在2个外键引用一个主键的表中插入数据...

代码如下:

create table Currency 
(
    ID int primary key identity(1,1),
    Code nvarchar(8) not null,
    Name nvarchar(128) not null,
    Is_Active bit not null default(0),
    Is_Base_Currency bit not null default(0),
    Country_id int foreign key(ID) references Country(ID) not null
)

Create table Currency_rate 
(
    ID int primary key identity(1,1),
    Currency_id int foreign key(ID) references Currency(ID) not null,
    Base_currency_id int foreign key(ID) references Currency(ID) not null,
    Rate decimal(16,6) not null,
    Ts datetime default getDate()
)

Insert into Currency_rate(Currency_id, Base_currency_id, Rate, Ts)
values (1, 1, 121212.212121, '2008-11-11 13:23:44.111'),
       (2, 2, 232323.323232, '2009-11-11 13:23:44.222'),
       (3, 3, 343434.434343, '2010-11-11 13:23:44.333')

这是我得到的错误:

  

信息547,级别16,状态0,第1行
  INSERT语句与FOREIGN KEY约束“ FK__Currency___Curre__239E4DCF”发生冲突。数据库“ CryptoCurrencyData”的表“ dbo.Currency”的列“ ID”中发生了冲突。   该声明已终止。

请帮助我-我找不到在网上冲浪的解决方案...

谢谢大家

关于, 埃里亚斯·H

1 个答案:

答案 0 :(得分:0)

创建约束是为了防止通过插入或更新表来破坏数据。

在您的情况下,您尝试插入不存在的数据。您正在尝试将Currency_rate表中不存在的ID's的值Currency插入Currency中。因此,这是约束的整个目标-防止数据损坏。

仅出于演示目的,我创建了Country表:

Create table Country (
  ID int primary key identity(1,1),
  CountryName nvarchar(50)
)

那么您的第一步将是:

INSERT INTO dbo.Country
(
    --ID - this column value is auto-generated
    CountryName
)
VALUES
(
    -- ID - int
    N'India' -- CountryName - nvarchar
)
, (N'Canada')
, (N'South America')

第二步将是:

INSERT INTO dbo.Currency
(
    --ID - this column value is auto-generated
    Code,
    Name,
    Is_Active,
    Is_Base_Currency,
    Country_id
)
VALUES
(
    -- ID - int
    N'Code1', -- Code - nvarchar
    N'India Currency', -- Name - nvarchar
    0, -- Is_Active - bit
    0, -- Is_Base_Currency - bit
    1 -- Country_id - int
)
, (
 N'Code2', -- Code - nvarchar
    N'Canada Currency', -- Name - nvarchar
    0, -- Is_Active - bit
    0, -- Is_Base_Currency - bit
    2 -- Country_id - int
)
, (
 N'Code3', -- Code - nvarchar
    N'South America Currency', -- Name - nvarchar
    0, -- Is_Active - bit
    0, -- Is_Base_Currency - bit
    3 -- Country_id - int
)

最后一步是:

Insert into Currency_rate(Currency_id,Base_currency_id,Rate,Ts)
values(1,1,121212.212121,'2008-11-11 13:23:44.111'),
(2,2,232323.323232,'2009-11-11 13:23:44.222'),
(3,3,343434.434343,'2010-11-11 13:23:44.333')