[英]SQL How to copy a master record with a unique ID and its relation entry
I have two tables, a master table and a relation table. 我有两个表,一个主表和一个关系表。 The Master table as an automatic identity ID field (DOCUMENT_ID) that is generated upon insert.
主表作为插入时生成的自动标识ID字段(DOCUMENT_ID)。 The relation table ties that DOCUMENT_ID from the master table with a USER_NAME entry.
关系表将主表中的DOCUMENT_ID与USER_NAME条目联系起来。 I want to be able to create a copy of the the record in the master table and a copy of its relation in the relationship table while establishing the new relation using the new automatically generated DOCUMENT_ID generated by the Master table.
我希望能够在使用主表生成的新自动生成的DOCUMENT_ID建立新关系的同时,在主表中创建记录的副本,并在关系表中创建其关系的副本。 Here is an example of my tables and the desired output.
这是我的表格和所需输出的示例。
MASTER TABLE: 主表:
DOCUMENT_ID | DOCUMENT_NAME
1 | Application
2 | Invoice
3 | Receipt
RELATION TABLE: 关系表:
DOCUMENT_ID| USER_NAME
1 | John
1 | Amy
2 | Jim
2 | Jane
3 | John
3 | Jane
I would like to copy the records from the master table and create a copy of the relationship so that my output looks like this: 我想从主表中复制记录并创建关系的副本,以便我的输出如下所示:
MASTER TABLE WITH NEW RECORDS INSERTED: Note that the DOCUMENT_ID column generated the IDs automatically. 插入了新记录的主表:请注意,DOCUMENT_ID列会自动生成ID。
DOCUMENT_ID | DOCUMENT_NAME
1 | Application
2 | Invoice
3 | Receipt
7 | Application
8 | Invoice
9 | Receipt
RELATION TABLE: This tables needs to tie the relation between the new IDs created in the master table and a copy of the USER_NAMES that were associated with the original DOCUMENT_IDs. 关系表:此表需要将在主表中创建的新ID与与原始DOCUMENT_ID关联的USER_NAMES副本之间的关系联系起来。
DOCUMENT_ID| USER_NAME
1 | John
1 | Amy
2 | Jim
2 | Jane
3 | John
3 | Jane
7 | John
7 | Amy
8 | Jim
8 | Jane
9 | John
9 | Jane
I had no time to test this TSQL but it should give you an idea: 我没有时间测试此TSQL,但它应该给您一个想法:
declare @documentID int
declare @newDocumentID int
declare @documentName VARCHAR(256)
declare master_cursor cursor for
select DOCUMENT_ID, DOCUMENT_NAME
from MASTER_TABLE
OPEN master_cursor
FETCH NEXT FROM master_cursor INTO @documentID, @documentName
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO MASTER_TABLE(DOCUMENT_NAME) VALUES (@documentName)
-- read the just inserted Document ID
SELECT @newDocumentID = MAX(DOCUMENT_ID)
FROM MASTER_TABLE
WHERE DOCUMENT_NAME = @documentName
-- now insert new values in relations table
INSERT INTO RELATIONS_TABLE
SELECT @newDocumentID, USER_NAME
FROM RELATIONS_TABLE
WHERE
DOCUMENT_ID = @documentID
FETCH NEXT FROM master_cursor INTO @documentID, @documentName
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.