insert语句和外键

时间:2017-02-19 21:23:37

标签: sql-server foreign-keys

我面临的错误:

  

INSERT语句与FOREIGN KEY约束冲突   “fk_anm_intake_code”。冲突发生在数据库“J.Does”中,   表“dbo.intake_codes”,列'intake_code'。声明一直如此   终止。

上述错误的脚本:

insert into animals
(anm_name,anm_species,anm_breed,anm_age,anm_gender,anm_size,anm_spayorneuter,anm_intake_date,anm_intake_code,anm_notes)
 values 
('Tom', 'Canine', 'Mix.pit/Poodle', 8.80, 'M', 'SM', 'Y', 12/23/16,'C', 'Needs additional water/Hoursebroken'),
('Chi', 'Feline', 'House', 0.80, 'F', 'SM', 'Y', 11/11/16, 'F', 'Very affectionate' ),
('Lin', 'Canine', 'Beagle', 2.30, 'M', 'SM', 'N', 1/17/16, 'B', 'Hoursebroken/loves to play ball'),
('Frisky', 'Feline', 'Mix.pit/Poodle', 11.50, 'F', 'Med',' N', 12/2/16, 'B', 'Best in low activity home'),
('Shady', 'Canine', 'House', 4.50, 'F', 'Med', 'Y', 1/16/17, 'C ', 'Null'),
('Sparky', 'Canine', 'Mix.pit/Poodle', 4.10, 'F', 'Lrg', 'N', 1/17/17, 'F', 'Not housebroken/love kids/gentle'),
('Lucy', 'Feline', 'House', 1.10, 'F', 'XL', 'Y', 12/3/16, 'E', 'Null'),
('Blue', 'Canine', 'Lab/Pit.Mixed', 1.20, 'F', 'SM', 'N', 2/4/17, 'B', 'Not housebroken')

请帮助!!

2 个答案:

答案 0 :(得分:0)

您必须尝试将值插入到dbo.intake_codes表中不存在的animals.anm_intake_code中。

查看您的查询...

INSERT INTO animals (
    anm_name,anm_species,anm_breed,anm_age,anm_gender,anm_size,anm_spayorneuter,anm_intake_date,anm_intake_code,anm_notes
) VALUES (
    'Tom', 'Canine', 'Mix.pit/Poodle', 8.80, 'M', 'SM', 'Y', 12/23/16,'C', 'Needs additional water/Hoursebroken'
), (
    'Chi', 'Feline', 'House', 0.80, 'F', 'SM', 'Y', 11/11/16, 'F', 'Very affectionate'
), (
    'Lin', 'Canine', 'Beagle', 2.30, 'M', 'SM', 'N', 1/17/16, 'B', 'Hoursebroken/loves to play ball'
), (
    'Frisky', 'Feline', 'Mix.pit/Poodle', 11.50, 'F', 'Med',' N', 12/2/16, 'B', 'Best in low activity home'
), (
    'Shady', 'Canine', 'House', 4.50, 'F', 'Med', 'Y', 1/16/17, 'C ', 'Null'
), (
    'Sparky', 'Canine', 'Mix.pit/Poodle', 4.10, 'F', 'Lrg', 'N', 1/17/17, 'F', 'Not housebroken/love kids/gentle'
), (
    'Lucy', 'Feline', 'House', 1.10, 'F', 'XL', 'Y', 12/3/16, 'E', 'Null'
), (
    'Blue', 'Canine', 'Lab/Pit.Mixed', 1.20, 'F', 'SM', 'N', 2/4/17, 'B', 'Not housebroken'
) 

...您正在尝试插入C' F' F' B' B'以及' E'。哪些值不在dbo.intake_codes中?

答案 1 :(得分:0)

您似乎没有在intake_code表中定义'N'dbo.intake_codes。您可以修复它插入缺失值

insert into dbo.intake_codes(intake_code) select 'N'