我正在尝试创建一个链接到多个角色的表。
该表称为 UserRoles,只有两列。
第一列包含对用户的引用
第二列包含指向角色的链接
我使用了 FOREIGN KEY REFERENCES,您可能会在底部注意到,但我一直收到错误消息
执行查询时出现以下错误:
Server: Msg 1770, Level 16, State 0, Line 1 Foreign key 'FK_UserRoles_user___70DDC3D8' references invalid column 'user_id' in referenced table 'MyUsers'.
无法创建约束。请参阅以前的错误。
有一个更好的方法吗?
CREATE TABLE MyUsers
(
id INT IDENTITY(1,1)PRIMARY KEY,
user_logon_id VARCHAR(30) NOT NULL,
user_full_name VARCHAR(30) NULL,
user_description VARCHAR(125) NULL,
user_password VARCHAR(125) NOT NULL,
);
INSERT INTO MyUsers (user_logon_id, user_full_name, user_description, user_password) VALUES ('mcobery', 'Marc Cobery',
CREATE TABLE MyRole
(
myrole_id INT IDENTITY(1,1)PRIMARY KEY,
role_name VARCHAR(30) NOT NULL,
role_description VARCHAR(50) NULL,
);
INSERT INTO MyRole (role_name, role_description) VALUES ('administrator', ' Administrator of the web site');
INSERT INTO MyRole (role_name, role_description) VALUES ('user', ' User of the web site');
CREATE TABLE UserRoles
(
user_id int FOREIGN KEY REFERENCES MyUsers(user_id),
role_id int FOREIGN KEY REFERENCES MyRole(role_id),
);
最佳答案
应该像下面这样
CREATE TABLE UserRoles
(
user_id int FOREIGN KEY REFERENCES MyUsers(id),
role_id int FOREIGN KEY REFERENCES MyRole(myrole_id),
);
MyUsers 表中不存在 user_id 列
关于sql-server - 带有 FOREIGN KEY REFERENCES 的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14999014/