2011-12-15 74 views
1

我剛剛添加了三個新列到Table A,我現在需要使用表TEXT中的主鍵填充。對於每個新單元,我需要創建一個新的TEXT記錄。使用新列創建新記錄並將其主鍵存儲在表中的每個新字段的最佳方法是什麼?將新外鍵插入新列

例如,如果Table A有10條記錄,我需要創建30(10 * 3)新TEXT記錄,並插入其ID添加到Table A使每個30個新細胞具有獨特的TEXT ID

回答

0
CREATE TABLE A 
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED 
    , Column1 INT NULL 
    , Column2 INT NULL 
    , Column3 INT NULL 
) 

CREATE TABLE TEXT 
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED 
    , [Column] INT NULL 
) 

INSERT INTO A (Column1, Column2, Column3) 
SELECT 1, 2, 3 

INSERT INTO A (Column1, Column2, Column3) 
SELECT 4, 5, 6 

INSERT INTO A (Column1, Column2, Column3) 
SELECT 7, 8, 9 

select ID, Column1, Column2, Column3 
from A 

select ID, [Column] 
FROM [TEXT] 

INSERT INTO TEXT([Column]) 
SELECT TEXTID 
FROM 
    (SELECT ID, Column1, Column2, Column3 
    FROM A) Tmp 
UNPIVOT 
    (TEXTID FOR A IN 
     (Column1 , Column2, Column3) 
)AS unpvt