2011-07-04 65 views
0

重複的記錄考慮下面的設計:與標識列

Company TABLE (
    CompanyId int NOT NULL IDENTITY PRIMARY KEY, 
    CompanyName nvarchar(max)) 
Product TABLE (
    ProductId int NOT NULL IDENTITY PRIMARY KEY, 
    CompanyId int NOT NULL, 
    ProductName nvarchar(max)) 
ProductPart TABLE (
    ProductPartId int NOT NULL IDENTITY PRIMARY KEY, 
    ProductId int NOT NULL, 
    ProductPartName) 

我需要複製一個公司(含CompanyId == @companyId)數據,以便它將包含完全相同的數據。

第一步是顯而易見的:

INSERT INTO Company(CompanyName) 
SELECT @newCompanyName 
FROM Company 
WHERE CompanyId = @companyId 

DECLARE @newCompanyId = SCOPE_IDENTITY() 

沒有ProductPart表這將是微不足道的複製Product數據以及:

INSERT INTO Product (ProductName) 
SELECT ProductName 
FROM Product 
WHERE CompanyId = @companyId 

但爲了正確地複製ProductPart數據,我需要有新老公司之間的產品映射數據。

我試圖用OUTPUT條款但遺憾的是它不支持我的方案:

DECLARE @productRemap TABLE (OldProductId int NOT NULL, NewProductId int NOT NULL PRIMARY KEY) 
INSERT INTO Product (ProductName) 
    OUTPUT ProductId, inserted.ProductId 
     INTO @productRemap 
SELECT ProductName 
FROM Product 
WHERE CompanyId = @companyId 
-- Invalid column name 'ProductId'. 

有什麼辦法將數據複製正確不涉及遊標?

+2

如果您使用SQL Server 2008,則可以使用'merge'代替。看看這個問題http://stackoverflow.com/questions/5365629/using-merge-output-to-get-mapping-between-source-id-and-target-id。 –

回答

2

謝謝到了Mikael我發現我可以實際使用的MERGE代替INSERT

DECLARE @productRemap 
    TABLE (OldProductId int NOT NULL, NewProductId int NOT NULL) 

-- Duplicate products 
MERGE INTO Product AS t 
USING (
    SELECT * 
    FROM Product 
    WHERE CompanyId = @companyId) AS s 
ON (0 = 1) 
WHEN NOT MATCHED THEN 
    INSERT (ProductName, CompanyId) 
    VALUES (ProductName, @newCompanyId) 
    OUTPUT s.ProductId, inserted.ProductId 
     INTO @productRemap; 

然後,我可以利用@productRemap映射插入ProductPart

MERGE INTO ProductPart AS t 
USING (
    SELECT * FROM ProductPart 
     INNER JOIN @productRemap ON ProductId = OldProductId) AS s 
ON (0 = 1) 
WHEN NOT MATCHED THEN 
    INSERT (ProductId, ProductPartName) 
    VALUES (NewProductId, ProductPartName) 
0

我明白你正在尋找與TSQL嚴格做到這一點,但是,形式的經驗,我發現最簡單的一個OldProductId場從添加到Product表和圖產品零件:

INSERT INTO Product (ProductName, OldProductId) 
SELECT ProductName, ProductId 
FROM Product 
WHERE CompanyId = @companyId 
+0

不幸的是,我不能添加任何額外的列到'產品'表 – Regent