如何在两个表中建立外键关系 [英] how to make FOREIGN KEY Relationship in Two table
问题描述
我已经创建了名为montage的数据库名称。同一数据库托管服务器。我无法备份服务器数据库。所以我是在本地创建的。我有两个表名
I have creating database name called montage. same database hosted server . i cant able to back up server database. so i am created locally . i have two table name called
1.TP_Users
2.TP_Roles
以下字段如下表
TP_Users
--------
Id PK, int, not null
UserName nvarchar(50), null
UserEmail nvarchar(50), null
DisplayName nvarchar(50), null
Password nvarchar(50), null
RoleId FK, int, not null -------------->Foreign key this make Relationship in TP_Roles Id column
IsActive bit, not null
ClientId int, null
另一个表TP_Roles跟随这样的字段
Another table TP_Roles following Fields like this
TP_Roles
--------
Id PK, int, not null
Role_Name varchar(200), null
IsActive bit, null
在服务器数据库中,我看到了关系表
i,如下所示
In server database i seen relationship table i seen Like following
FK Name Parent tabl name column_id Refrenced table name column_id
FK__Users_cop__RoleI__27AED5D5 TP_Users RoleId 6 TP_Roles Id 1
FK__Users_cop__RoleI__28A2FA0E TP_Users RoleId 6 TP_Roles Id 1
p>我像上面这样看到关系服务器数据库,但是当我像上面一样创建本地数据库时,如何创建本地数据库
I have See like Relationship server database above like this but when i create Local database same like above how can i create local database
推荐答案
您可以使用 添加外键约束ALTER TABLE
DDL语句:
You can add a foreign key constraint using the ALTER TABLE
DDL statement:
ALTER TABLE TP_Users
ADD CONSTRAINT FK_TP_Users_TP_Roles FOREIGN KEY (RoleId)
REFERENCES TP_Roles (Id )
ON DELETE CASCADE -- optional
ON UPDATE CASCADE -- optional
;
这篇关于如何在两个表中建立外键关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!