2017-10-10 96 views
0

我有兩個表與數據:GroupTable和PeopleTable。SQL Server:將表的行復制到同一個表

grouptable將有此列:ID,大陸,國家

PeopleTable有此列:ID,的groupId,名

的groupId是一個外鍵GroupTable.id

兩個表已填充從我的應用程序。我想要做的是創建一個存儲過程,將兩個表的內容複製到相同的表中,但更改GroupTable的continent列。因此,PeopleTable中的新行將指向GroupTable中的新行。輸入存儲過程是@sourceCont,@destinationCont

我有什麼:

GroupTable: 
     id | continent | company 
     0 | europe  |  aa 
     1 | europe  | bb 
     2 | europe  | cc 

PeopleTable: 
     id | groupId | name 
     0 |  0  | John 
     1 |  0  | Mary 
     2 |  0  | Nick 
     3 |  1  | Peter 
     4 |  2  | Michel 

這就是我想要的(@sourceCont =歐洲,@destinationCont =美國)

GroupTable: 
     id | continent | company 
     0 | europe  | aa 
     1 | europe  | bb 
     2 | europe  | cc 
     3 | america  | aa 
     4 | america  | bb 
     5 | america  | cc 
PeopleTable: 
     id | groupId | name 
     0 |  0  | John 
     1 |  0  | Mary 
     2 |  0  | Nick 
     3 |  1  | Peter 
     4 |  2  | Michel 
     5 |  3  | John 
     6 |  3  | Mary 
     7 |  3  | Nick 
     8 |  4  | Peter 
     9 |  5  | Michel 
+0

mysql或sql-server ....? – scaisEdge

回答

1
CREATE Proc Rocount 
@sourceCont NVARCHAR(50), @destinationCont NVARCHAR(50) 
AS 
BEGIN 
SET NOCOUNT ON 

DECLARE @String_sql NVARCHAR(MAX),@Maxid INT 

    --NOTE IF GroupID Is AUto Generated IN GroupTable 
    SET @String_sql='Insert INTO GroupTable 
        SELECT '''[email protected]+''' FROM GroupTable WHERE continent ='''[email protected]+''' ' 
    PRINT @String_sql 
    EXEC (@String_sql) 

    SELECT @Maxid= ID FROM GroupTable WHERE continent = @destinationCont 

    SET @String_sql='Insert INTO PeopleTable 
        SELECT ID,'''+CONVERT(NVARCHAR(2),@Maxid)+''',name 
        FROM PeopleTable WHERE GroupID IN (SELECT GroupID FROM GroupTable WHERE continent ='''[email protected]+''')' 
    PRINT @String_sql 
    EXEC (@String_sql) 




END 
+0

請檢查我編輯的問題 – aggicd

+0

基本上你不想創建一個新的組的副本,這是取決於現有的group.and是相同的PeopleTable.And是GroupId自動增量 –

+0

@aggicd我已經更新Ans檢查它 –

相關問題