2016-04-26 69 views
0

我有一個表結構,其中有子表中的FK列。如何在數據具有層次結構時創建數據的副本

所以說,有以下幾點:

Company 
-company_id 
-name 

Location 
-location_id 
-company_name 
-name 

Store 
-store_id 
-location_id 
-name 

Inventory 
-inventory_id 
-store_id 

現在我想建立一個公司的一個副本,其中所有的選址,店面和庫存的行一起。

所以說我想創建company_id = 123的副本,我必須複製所有行。

我嘗試這樣做:

DECLARE @OriginalCompanyId = 123 

DECALRE @companyId AS INT 

INSERT Companies (name) 
select c.name 
from companies c 
where c.companyId = @OrignalCOmpanyId 

SET @companyId = SCOPE_IDENTITY() 

但這種方法是行不通的,因爲其他表有多行,我將無法銜接新插入的PK值。

我應該採取什麼方法?

+0

這沒有意義 –

+0

@PouriaSharif什麼是沒有意義的? –

回答

0

我實際上一直在做一個這樣的項目。我的解決方案雖然不花哨,但迄今爲止已被證明是有效的。惱人的部分是設置過程。我很樂意接受批評和改進建議。

  1. 創建所有必要的表的「鏡子」模式/ DB(我已經有新的[ApplicationTableName])
  2. 對於每個PKEY/FKEY,創建一個「佔位符」列(我已經走了與p [ColumnName])
  3. 將現有數據映射到佔位符鍵,索引爲1.(這很煩人,但可以使用排名功能。)
  4. 通過佔位符鍵以降序插入到應用程序中(降序爲重要!)
  5. 使用排名函數更新您的「鏡像」表(請參閱示例)
  6. 根據需要重複使用所需的多個表格中的驅動/插入值。

例子:

鑑於此架構...

CREATE TABLE Accounts (
    AccountID int identity(1,1) not null, 
    Name varchar(500) not null 

) 

CREATE TABLE Users(
    UserID int identity(1,1) not null, 
    AccountID int not null, 
    Name varchar(500) not null 
) 

CREATE TABLE NewUsers(
    pUserID int not null, 
    UserID int not null, 
    AccountID int not null, 
    Name varchar(500) 
) 

而這個數據

INSERT INTO NewUsers VALUES 
(1,0,0,'Bob'), 
(2,0,0,'Sally'), 
(3,0,0,'Jeff'), 
(4,0,0,'Sam') 

說每次我們 「創造」 一個帳戶的時間,我們要創建這些4默認用戶...這看起來像這樣

DECLARE @AccountID int --this is scalar, so we'll use scope_identity() to grab it. 
INSERT INTO Account VALUES('MyNewAccountID') 
SELECT @AccountID = SCOPE_IDENTITY() 

--Prepare NewUsers w/ derived accountID 
UPDATE NewUsers SET AccountID = @AccountID 

--Do our "application" insert 
INSERT INTO Users(AccountID,Name) 

SELECT AccountID,Name 
FROM NewUsers 
ORDER BY pUserID DESC; 

--Capture inserted ID's for use in other tables (where we've derived pUserID) 
WITH InsertedUsers AS(
    SELECT 
     --use dense rank, it handles fkey mappings too 
     DENSE_RANK() OVER(ORDER BY UserID DESC) as pUserID, 
     UserID 
    FROM Users 
) 
UPDATE NewUsers SET UserID = iu.UserID 
FROM NewUsers nu 
JOIN InsertedUsers iu 
ON iu.pUserID = nu.pUserID 


SELECT TOP 100 * FROM Account ORDER BY 1 DESC 
SELECT TOP 100 * FROM Users ORDER BY 1 DESC 

所以,現在如果未來表需要UserID進入應用程序(並且具有派生pUserID,),我們可以通過加入pUserID從NewUsers獲取它。