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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With