SQL 外键引用无效表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20107178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Foreign key references invalid table
提问by ojek
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'.
.
外键抛出一个错误说Foreign key 'FK__Number__Name__1CF15040' references invalid table 'Users.Name'.
.
What did I do wrong?
我做错了什么?
采纳答案by Santhosh
回答by Anderson Silva
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
)
回答by Zoran P.
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.
对于像我一样 100% 肯定 Table 确实存在的人,请务必检查 web.config。我在那里有一个错字,它给出了这个错误,如果你问我这是违反直觉的,但就是这样。
回答by NoChance
You should reference the Primary Key of test.dbo.users.
您应该引用 test.dbo.users 的主键。
In SQL Server you could do this:
在 SQL Server 中,您可以这样做:
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....
在上面,您有 2 个表之间的强制关联。如果您想拥有可选关系,请从 Id_Fk 中删除“非空”....
Note: I don't know what is the Name column for.
注意:我不知道 Name 列是做什么用的。
回答by Kamil D
use [database];
and then create table. Works for me.
然后创建表。为我工作。