Foreign key reference problem, SQL Server












0














I'm having trouble understanding how to setup my foreign key reference. I'm trying to make a reference between tables Lägenheter and Arbetslista so that one row in Lägenheter belong to many rows in Arbetslista.



I have created tables likes this:



CREATE TABLE Deltagare (
Deltagarnr int PRIMARY KEY,
Namn varchar(30),
Typ varchar(30)
);

CREATE TABLE Uppgifter (
Uppgift varchar(30) PRIMARY KEY,
Typ varchar(30),
Pris money
);

CREATE TABLE Arbetslista (
Deltagarnr int not null,
Datum date not null,
Uppgift varchar(30) not null,
Lägenhetsnr int not null,

PRIMARY KEY (Deltagarnr, Datum, Uppgift),
FOREIGN KEY (Deltagarnr) REFERENCES Deltagare(Deltagarnr),
FOREIGN KEY (Uppgift) REFERENCES Uppgifter(Uppgift)
);


Then I import some data from a .mdb file to all three tables.
After that I add another table:



CREATE TABLE Lägenheter(
lägenhetsnummer int PRIMARY KEY,
gatuadress varchar(30),
kvadrater int
);


It all works fine until this last step:



ALTER TABLE Arbetslista
ADD FOREIGN KEY (Lägenhetsnr) REFERENCES Lägenheter(lägenhetsnummer)
;


Here I get this error message:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Arbetslis__Lägen__403A8C7D". The conflict occurred in database "Hushåll", table "dbo.Lägenheter", column 'lägenhetsnummer'.



After that I have also tried to delete all data from Arbetslista and then execute the mentioned ALTER TABLE again. It works, but then I get an error trying to import the data again:



Hresult: 0x80004005 Description: "The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Arbetslis__Lägen__412EB0B6". The conflict occurred in database "Hushåll", table "dbo.Lägenheter", column 'lägenhetsnummer'.".
(SQL Server Import and Export Wizard)



Why is this not possible when the other foreign keys seems to work fine?










share|improve this question




















  • 1




    Are you putting the required data in Lägenheter?
    – Mat
    Nov 13 '18 at 9:48










  • And are you inserting the data inside a transaction into both tables?
    – Sebastian S.
    Nov 13 '18 at 9:50










  • Side note: Please learn to name your constraints. It makes things a lot more pleasant if you later need to e.g. drop some of them.
    – Damien_The_Unbeliever
    Nov 13 '18 at 10:24
















0














I'm having trouble understanding how to setup my foreign key reference. I'm trying to make a reference between tables Lägenheter and Arbetslista so that one row in Lägenheter belong to many rows in Arbetslista.



I have created tables likes this:



CREATE TABLE Deltagare (
Deltagarnr int PRIMARY KEY,
Namn varchar(30),
Typ varchar(30)
);

CREATE TABLE Uppgifter (
Uppgift varchar(30) PRIMARY KEY,
Typ varchar(30),
Pris money
);

CREATE TABLE Arbetslista (
Deltagarnr int not null,
Datum date not null,
Uppgift varchar(30) not null,
Lägenhetsnr int not null,

PRIMARY KEY (Deltagarnr, Datum, Uppgift),
FOREIGN KEY (Deltagarnr) REFERENCES Deltagare(Deltagarnr),
FOREIGN KEY (Uppgift) REFERENCES Uppgifter(Uppgift)
);


Then I import some data from a .mdb file to all three tables.
After that I add another table:



CREATE TABLE Lägenheter(
lägenhetsnummer int PRIMARY KEY,
gatuadress varchar(30),
kvadrater int
);


It all works fine until this last step:



ALTER TABLE Arbetslista
ADD FOREIGN KEY (Lägenhetsnr) REFERENCES Lägenheter(lägenhetsnummer)
;


Here I get this error message:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Arbetslis__Lägen__403A8C7D". The conflict occurred in database "Hushåll", table "dbo.Lägenheter", column 'lägenhetsnummer'.



After that I have also tried to delete all data from Arbetslista and then execute the mentioned ALTER TABLE again. It works, but then I get an error trying to import the data again:



Hresult: 0x80004005 Description: "The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Arbetslis__Lägen__412EB0B6". The conflict occurred in database "Hushåll", table "dbo.Lägenheter", column 'lägenhetsnummer'.".
(SQL Server Import and Export Wizard)



Why is this not possible when the other foreign keys seems to work fine?










share|improve this question




















  • 1




    Are you putting the required data in Lägenheter?
    – Mat
    Nov 13 '18 at 9:48










  • And are you inserting the data inside a transaction into both tables?
    – Sebastian S.
    Nov 13 '18 at 9:50










  • Side note: Please learn to name your constraints. It makes things a lot more pleasant if you later need to e.g. drop some of them.
    – Damien_The_Unbeliever
    Nov 13 '18 at 10:24














0












0








0







I'm having trouble understanding how to setup my foreign key reference. I'm trying to make a reference between tables Lägenheter and Arbetslista so that one row in Lägenheter belong to many rows in Arbetslista.



I have created tables likes this:



CREATE TABLE Deltagare (
Deltagarnr int PRIMARY KEY,
Namn varchar(30),
Typ varchar(30)
);

CREATE TABLE Uppgifter (
Uppgift varchar(30) PRIMARY KEY,
Typ varchar(30),
Pris money
);

CREATE TABLE Arbetslista (
Deltagarnr int not null,
Datum date not null,
Uppgift varchar(30) not null,
Lägenhetsnr int not null,

PRIMARY KEY (Deltagarnr, Datum, Uppgift),
FOREIGN KEY (Deltagarnr) REFERENCES Deltagare(Deltagarnr),
FOREIGN KEY (Uppgift) REFERENCES Uppgifter(Uppgift)
);


Then I import some data from a .mdb file to all three tables.
After that I add another table:



CREATE TABLE Lägenheter(
lägenhetsnummer int PRIMARY KEY,
gatuadress varchar(30),
kvadrater int
);


It all works fine until this last step:



ALTER TABLE Arbetslista
ADD FOREIGN KEY (Lägenhetsnr) REFERENCES Lägenheter(lägenhetsnummer)
;


Here I get this error message:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Arbetslis__Lägen__403A8C7D". The conflict occurred in database "Hushåll", table "dbo.Lägenheter", column 'lägenhetsnummer'.



After that I have also tried to delete all data from Arbetslista and then execute the mentioned ALTER TABLE again. It works, but then I get an error trying to import the data again:



Hresult: 0x80004005 Description: "The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Arbetslis__Lägen__412EB0B6". The conflict occurred in database "Hushåll", table "dbo.Lägenheter", column 'lägenhetsnummer'.".
(SQL Server Import and Export Wizard)



Why is this not possible when the other foreign keys seems to work fine?










share|improve this question















I'm having trouble understanding how to setup my foreign key reference. I'm trying to make a reference between tables Lägenheter and Arbetslista so that one row in Lägenheter belong to many rows in Arbetslista.



I have created tables likes this:



CREATE TABLE Deltagare (
Deltagarnr int PRIMARY KEY,
Namn varchar(30),
Typ varchar(30)
);

CREATE TABLE Uppgifter (
Uppgift varchar(30) PRIMARY KEY,
Typ varchar(30),
Pris money
);

CREATE TABLE Arbetslista (
Deltagarnr int not null,
Datum date not null,
Uppgift varchar(30) not null,
Lägenhetsnr int not null,

PRIMARY KEY (Deltagarnr, Datum, Uppgift),
FOREIGN KEY (Deltagarnr) REFERENCES Deltagare(Deltagarnr),
FOREIGN KEY (Uppgift) REFERENCES Uppgifter(Uppgift)
);


Then I import some data from a .mdb file to all three tables.
After that I add another table:



CREATE TABLE Lägenheter(
lägenhetsnummer int PRIMARY KEY,
gatuadress varchar(30),
kvadrater int
);


It all works fine until this last step:



ALTER TABLE Arbetslista
ADD FOREIGN KEY (Lägenhetsnr) REFERENCES Lägenheter(lägenhetsnummer)
;


Here I get this error message:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Arbetslis__Lägen__403A8C7D". The conflict occurred in database "Hushåll", table "dbo.Lägenheter", column 'lägenhetsnummer'.



After that I have also tried to delete all data from Arbetslista and then execute the mentioned ALTER TABLE again. It works, but then I get an error trying to import the data again:



Hresult: 0x80004005 Description: "The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Arbetslis__Lägen__412EB0B6". The conflict occurred in database "Hushåll", table "dbo.Lägenheter", column 'lägenhetsnummer'.".
(SQL Server Import and Export Wizard)



Why is this not possible when the other foreign keys seems to work fine?







sql-server ssms






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 11:48









Birel

436113




436113










asked Nov 13 '18 at 9:44









CrockyCrocky

12




12








  • 1




    Are you putting the required data in Lägenheter?
    – Mat
    Nov 13 '18 at 9:48










  • And are you inserting the data inside a transaction into both tables?
    – Sebastian S.
    Nov 13 '18 at 9:50










  • Side note: Please learn to name your constraints. It makes things a lot more pleasant if you later need to e.g. drop some of them.
    – Damien_The_Unbeliever
    Nov 13 '18 at 10:24














  • 1




    Are you putting the required data in Lägenheter?
    – Mat
    Nov 13 '18 at 9:48










  • And are you inserting the data inside a transaction into both tables?
    – Sebastian S.
    Nov 13 '18 at 9:50










  • Side note: Please learn to name your constraints. It makes things a lot more pleasant if you later need to e.g. drop some of them.
    – Damien_The_Unbeliever
    Nov 13 '18 at 10:24








1




1




Are you putting the required data in Lägenheter?
– Mat
Nov 13 '18 at 9:48




Are you putting the required data in Lägenheter?
– Mat
Nov 13 '18 at 9:48












And are you inserting the data inside a transaction into both tables?
– Sebastian S.
Nov 13 '18 at 9:50




And are you inserting the data inside a transaction into both tables?
– Sebastian S.
Nov 13 '18 at 9:50












Side note: Please learn to name your constraints. It makes things a lot more pleasant if you later need to e.g. drop some of them.
– Damien_The_Unbeliever
Nov 13 '18 at 10:24




Side note: Please learn to name your constraints. It makes things a lot more pleasant if you later need to e.g. drop some of them.
– Damien_The_Unbeliever
Nov 13 '18 at 10:24












2 Answers
2






active

oldest

votes


















0














There are rows in Arbetslista table, for which the value of Lägenhetsnr doesn't exists in field lägenhetsnummer of table Lägenheter. You must clean the existing data to be able to create the foreign key like that.



Check your data by executing this script:



select * from Arbetslista a where not exists (select * from Lägenheter l where l.lägenhetsnummer = a.Lägenhetsnr)





share|improve this answer





























    0














    After importing the data into Arbetslista, the column Lägenhetsnr was initialize to some value ( say XYZ).
    later, when trying to add the FOREIGN KEY to Arbetslista, SQL try to meet this, however it cannot find row with primary key lägenhetsnummer = XYZ and the statement would be terminated.
    I think the best is to create the 4 table first then clean the data and try to import it.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53278067%2fforeign-key-reference-problem-sql-server%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      There are rows in Arbetslista table, for which the value of Lägenhetsnr doesn't exists in field lägenhetsnummer of table Lägenheter. You must clean the existing data to be able to create the foreign key like that.



      Check your data by executing this script:



      select * from Arbetslista a where not exists (select * from Lägenheter l where l.lägenhetsnummer = a.Lägenhetsnr)





      share|improve this answer


























        0














        There are rows in Arbetslista table, for which the value of Lägenhetsnr doesn't exists in field lägenhetsnummer of table Lägenheter. You must clean the existing data to be able to create the foreign key like that.



        Check your data by executing this script:



        select * from Arbetslista a where not exists (select * from Lägenheter l where l.lägenhetsnummer = a.Lägenhetsnr)





        share|improve this answer
























          0












          0








          0






          There are rows in Arbetslista table, for which the value of Lägenhetsnr doesn't exists in field lägenhetsnummer of table Lägenheter. You must clean the existing data to be able to create the foreign key like that.



          Check your data by executing this script:



          select * from Arbetslista a where not exists (select * from Lägenheter l where l.lägenhetsnummer = a.Lägenhetsnr)





          share|improve this answer












          There are rows in Arbetslista table, for which the value of Lägenhetsnr doesn't exists in field lägenhetsnummer of table Lägenheter. You must clean the existing data to be able to create the foreign key like that.



          Check your data by executing this script:



          select * from Arbetslista a where not exists (select * from Lägenheter l where l.lägenhetsnummer = a.Lägenhetsnr)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 13 '18 at 9:49









          Andrey NikolovAndrey Nikolov

          3,5031620




          3,5031620

























              0














              After importing the data into Arbetslista, the column Lägenhetsnr was initialize to some value ( say XYZ).
              later, when trying to add the FOREIGN KEY to Arbetslista, SQL try to meet this, however it cannot find row with primary key lägenhetsnummer = XYZ and the statement would be terminated.
              I think the best is to create the 4 table first then clean the data and try to import it.






              share|improve this answer




























                0














                After importing the data into Arbetslista, the column Lägenhetsnr was initialize to some value ( say XYZ).
                later, when trying to add the FOREIGN KEY to Arbetslista, SQL try to meet this, however it cannot find row with primary key lägenhetsnummer = XYZ and the statement would be terminated.
                I think the best is to create the 4 table first then clean the data and try to import it.






                share|improve this answer


























                  0












                  0








                  0






                  After importing the data into Arbetslista, the column Lägenhetsnr was initialize to some value ( say XYZ).
                  later, when trying to add the FOREIGN KEY to Arbetslista, SQL try to meet this, however it cannot find row with primary key lägenhetsnummer = XYZ and the statement would be terminated.
                  I think the best is to create the 4 table first then clean the data and try to import it.






                  share|improve this answer














                  After importing the data into Arbetslista, the column Lägenhetsnr was initialize to some value ( say XYZ).
                  later, when trying to add the FOREIGN KEY to Arbetslista, SQL try to meet this, however it cannot find row with primary key lägenhetsnummer = XYZ and the statement would be terminated.
                  I think the best is to create the 4 table first then clean the data and try to import it.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 13 '18 at 15:16









                  Birel

                  436113




                  436113










                  answered Nov 13 '18 at 10:20









                  Ahmed BahtityAhmed Bahtity

                  17925




                  17925






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53278067%2fforeign-key-reference-problem-sql-server%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Xamarin.iOS Cant Deploy on Iphone

                      Glorious Revolution

                      Dulmage-Mendelsohn matrix decomposition in Python