从其他表复制/克隆记录及其所有子行

时间:2019-01-16 16:20:46

标签: sql sql-server

我需要一个SQL查询来从其他表复制/克隆一行及其所有子级。假设我有3张这样的桌子。

CREATE TABLE [dbo].[Order]
(
    [OrderID] [int] IDENTITY(1,1) NOT NULL,
    [CustomerName] [varchar](20) NULL
)

CREATE TABLE [dbo].[OrderDetail]
(
    [OrderDetailID] [int] IDENTITY(1,1) NOT NULL,
    [OrderID] [int] NOT NULL,
    [Detail] [varchar](20) NULL
)

CREATE TABLE [dbo].[CustomProduct]
(
    [CustomProductID] [int] IDENTITY(1,1) NOT NULL,
    [OrderDetailID] [int] NOT NULL,
    [Custom] [varchar](20) NULL
)

INSERT INTO Order 
VALUES ('Customer1'),('Customer2')

INSERT INTO OrderDetail 
VALUES (1, 'Customer1_Detail_1'), (1, 'Customer1_Detail_2'),
       (2, 'Customer2_Detail_1'), (2, 'Customer2_Detail_2')

INSERT INTO CustomProduct 
VALUES (1, 'Customer1_Detail_1_Custom1'),
       (1, 'Customer1_Detail_1_Custom2'),
       (2, 'Customer1_Detail_2_Custom1'),
       (2, 'Customer1_Detail_2_Custom2'),
       (3, 'Customer2_Detail_1_Custom1'),
       (3, 'Customer2_Detail_1_Custom2'),
       (4, 'Customer2_Detail_2_Custom1'),
       (4, 'Customer2_Detail_2_Custom1')

数据将如下所示:

订单

1   Customer1
2   Customer2

订单详细信息

1   1   Customer1_Detail_1
2   1   Customer1_Detail_2
3   2   Customer2_Detail_1
4   2   Customer2_Detail_2

自定义产品

1   1   Customer1_Detail_1_Custom1
2   1   Customer1_Detail_1_Custom2
3   2   Customer1_Detail_2_Custom1
4   2   Customer1_Detail_2_Custom2
5   3   Customer2_Detail_1_Custom1
6   3   Customer2_Detail_1_Custom2
7   4   Customer2_Detail_2_Custom1
8   4   Customer2_Detail_2_Custom1

现在,我需要一个SQL查询来将Order1克隆到New Order及其所有子行中。像这样:

订单

1   Customer1
2   Customer2
3   Customer1_cloned

订单详细信息

1   1   Customer1_Detail_1
2   1   Customer1_Detail_2
3   2   Customer2_Detail_1
4   2   Customer2_Detail_2
5   3   Customer1_Detail_1_cloned
6   3   Customer1_Detail_2_cloned

自定义产品

1   1   Customer1_Detail_1_Custom1
2   1   Customer1_Detail_1_Custom2
3   2   Customer1_Detail_2_Custom1
4   2   Customer1_Detail_2_Custom2
5   3   Customer2_Detail_1_Custom1
6   3   Customer2_Detail_1_Custom2
7   4   Customer2_Detail_2_Custom1
8   4   Customer2_Detail_2_Custom1
9   5   Customer1_Detail_1_Custom1_cloned
10  5   Customer1_Detail_1_Custom2_cloned
11  6   Customer1_Detail_2_Custom1_cloned
12  6   Customer1_Detail_2_Custom2_cloned

This answer is similar but not as I Expected 基于该解决方案,您必须首先克隆CustomProduct(子表),然后 插入要插入的父母的ID或身份列。就我而言,由于ID会自动递增,因此我们找不到要插入父表的任何身份。

0 个答案:

没有答案