简体   繁体   English

如何将一个表的自动生成的ID插入另一表的ID

[英]How to insert an auto-generated ID of one table into another table's ID

I am trying to make a project which is an Online shopping website. 我正在尝试制作一个在线购物网站的项目。 I have three tables,namely, Category Table, Sub-Category Table and Products table. 我有三个表,即类别表,子类别表和产品表。 In category table I have CategoryID and CategoryName as the two fileds.In Sub-Category table I have CategoryID , Sub-CategoryID and SubCategoryName as the fields, and in products table I have CategoryID , SubCategoryID , ProductID and ProductName . 在类别表中,我将CategoryIDCategoryName作为两个文件。在子类别表中,我将CategoryIDSub-CategoryIDSubCategoryName作为字段,在产品表中,我将CategoryIDSubCategoryIDProductIDProductName

Now in category table , the categoryID is autogenerated and set as primary key.In sub-Category table, the none of the keys are auto generated and both the categoryID and subCategory ID are set to combined primary keys. 现在,在类别表中,将自动生成categoryID并将其设置为主键。在子类别表中,将不会自动生成任何键,并且将categoryID和subCategory ID都设置为组合的主键。 Now ,when I insert a categoryName into the category table, I want the CategoryID(auto-generated) to be inserted in the categoryID column of the SubCategory table and the CategoryID column of the ProductTable. 现在,当我将categoryName插入类别表时,我希望将CategoryID(自动生成)插入SubCategory表的categoryID列和ProductTable的CategoryID列。 There is a lot of content in the net on this matter, but none solves exactly my problem. 网络上有很多关于这个问题的内容,但是没有一个能完全解决我的问题。

I feel there is a bad smell in your design. 我觉得您的设计中有难闻的气味。

You do not need to have a composite primary key in your sub tables since you already have a unique identifier defined in your table. 您不需要在子表中使用复合主键,因为您已经在表中定义了唯一的标识符。 Instead, just use one column as a primary key and add foreign key relations to your sub tables. 相反,只需将一列用作主键,然后将外键关系添加到子表中。

I think You shud user SCOPE_IDENTITY for that 我认为您为此用户SCOPE_IDENTITY

SCOPE_IDENTITY returns the last identity value generated for any table. SCOPE_IDENTITY返回为任何表生成的最后一个标识值。

INSERT INTO Category (....) VALUES(....)

DECLARE @id int;
SELECT @id=SCOPE_IDENTITY();

INSERT INTO Subcategory(CatagoryID,....) VALUES(@id,....)
INSERT INTO Product (CategoryID,....) Values(@id,...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM