Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key references invalid table

Tags:

sql

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?

like image 680
ojek Avatar asked Nov 20 '13 21:11

ojek


People also ask

Can a foreign key reference a table?

A Foreign Key is a database key that is used to link two tables together. The FOREIGN KEY constraint identifies the relationships between the database tables by referencing a column, or set of columns, in the Child table that contains the foreign key, to the PRIMARY KEY column or set of columns, in the Parent table.

How do I find a foreign key reference in a table?

To view the foreign key attributes of a relationship in a specific table. Open the Table Designer for the table containing the foreign key you want to view, right-click in the Table Designer, and choose Relationships from the shortcut menu.

Can a foreign key reference two tables?

The FOREIGN KEY constraint is a key used to link two tables together. A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.


2 Answers

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
)
like image 45
Anderson Silva Avatar answered Sep 29 '22 02:09

Anderson Silva


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.

like image 95
NoChance Avatar answered Sep 29 '22 01:09

NoChance