SQL Server 键和外键
如果我在同一个数据库的表 A 和表 B 中有主键(表 B 有自己的主键),我将与表 A 中的主键创建关系,以便表 B 中的列是外键,这意味着在表 A 的主键列中创建的主键数据也将添加到表 B 中,因为它是外键列,或者我是否必须对该关系进行编码,如果是这样,我该如何处理?
If I have a primary key in table A and in table B of the same database (table B has its own primary key) I create a relationship with the primary key in table A so that a column in table B is the foreign key, does it mean that the primary key data created in the primary key column of table A will also be added to table B by virtue of it being a foreign key column or do I have to code that relationship, and if so how do I go about that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
回答你的问题:
您将需要定义两个表之间的关系。示例:
当您将记录插入 tableB 时,您仍然需要定义 tableAId。 SQL Server 并不神奇地知道这应该是什么。
因此,假设如果 tableA 看起来像这样:
要在 tableB 中插入引用记录 2 的记录,您需要执行以下操作:
假设 tableB 具有以下结构:
In response to your question:
You will need to define the relationships between the two tables. Example:
When you insert a record into tableB you will still need to define tableAId is. SQL Server doesn't magically know what this should be.
So hypothetically if tableA looked like this:
To insert a record in tableB that referenced record 2 you would need to do this:
This assumes tableB has the following structure:
您的问题:这是否意味着在A表的主键列中创建的主键数据也会因为它是外键列而被添加到B表中
?不,外键不会将数据输入到其他表中。在插入引用表 B 中的外键的记录之前,您将需要表 A 中的一条记录。
问#2:或者我是否必须对该关系进行编码,如果需要,我该如何处理?
插入表A,然后插入表B。如果您愿意,可以在表A上放置一个触发器,以便在将数据输入表A时将记录插入表B...
Your Q : does it mean that the primary key data created in the primary key column of table A will also be added to table B by virtue of it being a foreign key column
Nope, foriegn keys will not enter data into other tables. You will need a record in Table A before you insert a record referencing that foriegn key in Table B.
Q # 2 : or do I have to code that relationship, and if so how do I go about that?
insert into tableA, then insert into Table B. A trigger could be put on TableA to insert a record into TableB when data was entered into tableA had you wanted...
我不完全确定你在问什么,但是如果你想在表A中插入一条记录,在表B中插入一条相关记录,那么你必须指定表A记录中的id作为外键中的值表 B 中的字段。
以下是一个示例:表author 有字段
id
和name
。现在表 book 有字段
id
、author_id
和title
。如果作者的
id
字段是自动生成的,则您无需在插入语句中指定它,并且可以使用 @@IDENTITY 属性。I'm not entirely sure what you're asking, but if you want to insert one record into table A and a related record into table B, then you have to specify the id from the table A record as the value in the foreign key field in table B.
Here's an example: table author has fields
id
andname
.Now table book has fields
id
,author_id
andtitle
.If the author's
id
field is automatically generated, then you would not specify it in the insert statement, and you would retrieve its value using the @@IDENTITY property.