2016-06-22 4 views
1

CustomerテーブルにプライマリキーとしてCustomerId、外部キーとしてParentCustomerIdが含まれており、それぞれのレコードを作成するinsert文をカスケードしたいとします。階層チェーンの顧客。CTEを使用して複数のレコードを階層に基づいて挿入する方法

Customer1:CustomerId: 1ParentCustomerId: Null

Customer2:私は、次があれば

は、私はまた、CustomerContactのCustomerIdPersonIdのクラスタ化された主キーを持つテーブル、およびSO DateCreated

を持ってCustomerId: 2ParentCustomerId: 1

カスタマー3:CustomerId: 3ParentCustomerId: 2

そして、私は顧客ごとに別のテーブルに行を挿入するように(この場合は3が可変であるが、階層が深く行くことができる)私は私の顧客IDに1を渡すが、私は3を作成したいですチェーン内にある。

declare @1 as int  --customerId 
declare @2 as int  --personId for the contact 
declare @3 as datetime --DateCreated 

set @1 = 1 
set @2 = 1 --personId 
set @3 = GetDate() 

--I don't know how to use a CTE to get all the CustomerIds that are 
-- 
--something like 
--with cte_customers 
--as 
--(select CustomerId from customer 
-- where ParentCustomerId = @1 
--) 

insert into CustomerContact 
Values(@1, @2, @3) 

は、どのように私はCTEが01​​をPARAMし、それぞれのCustomerContactにレコードを作成するために、関連するすべての顧客の子供を取得するために書くことができますか?

+2

'再帰的なcte'を使用する必要があります –

+0

' set @ 1 = 1'とは何ですか?いくつかの言語拡張?スカラー定数? – wildplasser

+0

@wildplasserが最後のクエリでは@ 1がパラメータになります。私はそれを賢明な例を作るために1に設定しました(または少なくとも試して) –

答えて

1

union allを使用してrecursive common table expressionを使用する必要があります。例を以下に示します。

with cte as (
    select customerid, parentcustomerid 
    from customer 
    where customerid = 1 
    union all 
    select c.customerid, cte.customerid 
    from customer c join cte on cte.customerid = c.parentcustomerid) 

insert into customercontact 
select customerId, @1, @2 from cte 

サンプルデータを使用すると、3つのレコードが返され、より深い関係も処理できます。

+0

です。それを 'cteからselect customeridに変更した場合、返される各customerIdのレコードを作成するために、私のinsertステートメントを記述しますか? –

+1

@ USER_8675309 - 私は次のように言っていますが、これは何かを指しています: 'insert into CustomerContact select customerid、@ 2、@ 3 from cte'? – sgeddes

+0

"を入力してください。 カスタマーコンタクトに挿入する(customerid、@ 2、@ 3) next"は私が行っていることです。 VB.Netのような構文を許してください –

関連する問題