Foreign Key References Invalid Table

I have the following code:

create table test.dbo.Users
(
    Id int identity(1,1) primary key,
    Name varchar(36) not null
)

create table test.dbo.Number
(
    Id int identity(1,1) primary key,
    Number varchar(10) not null,
    Name varchar(36) not null foreign key references Users.Name
)

The foreign key throws an error saying Foreign key 'FK__Number__Name__1CF15040' references invalid table 'Users.Name'..

What did I do wrong?

2

6 Answers

Please see in this SQLfiddle link, Link

CREATE TABLE NUMBER(
    ID INT PRIMARY KEY, 
    NUMBER VARCHAR(10) NOT NULL,
    NAME VARCHAR(36) NOT NULL REFERENCES USERS(NAME)
);

Foreign key must reference a primary key in another table

I would use the following code

I hope it is useful

use test
create table test.dbo.Users
(
    Id int identity(1,1) primary key,
    Name varchar(36) not null
)

create table test.dbo.Number
(
    Id int identity(1,1) primary key,
    Number varchar(10) not null,
    Users_Id int not null

    constraint fk_Number_Users foreign key (Users_Id) 
               references Users(Id)
               on update no action
               on delete no action
)

You should reference the Primary Key of test.dbo.users.

In SQL Server you could do this:

create table Number
(
    Id int identity(1,1) primary key,
    Number varchar(10) not null,
    Name varchar(36) not null ,
    Id_FK int not null foreign key references Users(id)
)

In the above, you have a mandatory association between the 2 tables. If you want to have optional relationship, remove the 'not null' from Id_Fk....

Note: I don't know what is the Name column for.

1

For people who were 100% positive that Table does exist, like I was, please be sure to check web.config. I had a typo in there and it was giving this error, which is counter-intuitive if you ask me, but that's the case.

If you are running a bunch of scripts to create tables, It might worth to make sure the referenced table script is running before the consumer table.

use [database];

and then create table. Works for me.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest