2017-10-10 12 views
0

データが2つあるテーブル: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

基本的には、既存のグループに依存する新しいグループのレプリカを作成することはできません。また、PeopleTableと同じです。GroupId自動インクリメント –

+0

@aggicd私はAnsをチェックしました –

関連する問題