0

我正在迁移一个数据库模型,我必须将关系更改为1:n关系n:m

我需要INSERT将数据放入新表并使用ID在过程中生成的数据来填充连接表。

这些表被称为Parts并且Document它们之间的连接表被称为PartDocument

现在我想documents为每个创建两个唯一的(具有默认类型/名称/描述) ,并通过连接表part将它们链接到相应的。part我可以轻松地创建 2*N documents,但我很难弄清楚如何将每个链接到PartDocument连接表。

INSERT INTO Document (Type, Name, Description)
SELECT 1, 'Work Instructions', 'Work Instructions'
FROM Parts
GO

INSERT INTO Document (Type, Name, Description)
SELECT 2, 'Drawing', 'Drawing'
FROM Parts
GO

INSERT INTO PartDocument (PartID, DocumentID)
?????

我的PartDocument连接表只有两列PartIDDocumentID,它们一起用作复合键。

我想要的结果是每个部分都有两个文档,它们每个都将通过连接表与相应的部分链接。

我正在使用 SQL Server Express 2012。 http://sqlfiddle.com/#!6/b51f0

4

2 回答 2

1

我最终做的是在创建 Document 表时添加一个临时 PartID 列。然后我可以在创建并链接文档后删除此列。

所以基本上是这样的:

INSERT INTO Document (Type, Name, Description, PartID)
SELECT 1, 'Work Instructions', 'Work Instructions', Part.ID
FROM Part
GO

INSERT INTO PartDocument
SELECT Document.PartID, Document.ID
FROM Document
GO

ALTER TABLE Document
DROP COLUMN PartID
GO
于 2013-05-21T06:16:12.397 回答
0
INSERT INTO Document (Type, Name, Description)
SELECT 1, 'Work Instructions', 'Work Instructions'
FROM Parts
GO

INSERT INTO Document (Type, Name, Description)
SELECT 2, 'Drawing', 'Drawing'
FROM Parts
GO

INSERT INTO PartDocument (PartID, DocumentID)
SELECT part.id, document.id
FROM Parts part
INNER JOIN Document document ON part.field1 = document.field1
GO

复杂元素是最后一个选择中的ON部分。INNER JOIN您必须选择刚刚创建的线条以及它们来自的部件元素。

于 2013-05-20T22:06:28.533 回答