Customer
テーブルにプライマリキーとしてCustomerId
、外部キーとしてParentCustomerId
が含まれており、それぞれのレコードを作成するinsert文をカスケードしたいとします。階層チェーンの顧客。CTEを使用して複数のレコードを階層に基づいて挿入する方法
Customer1:CustomerId: 1
:ParentCustomerId: Null
Customer2:私は、次があれば
は、私はまた、CustomerContactのCustomerId
、PersonId
のクラスタ化された主キーを持つテーブル、およびSO DateCreated
を持ってCustomerId: 2
:ParentCustomerId: 1
カスタマー3:CustomerId: 3
:ParentCustomerId: 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
にレコードを作成するために、関連するすべての顧客の子供を取得するために書くことができますか?
'再帰的なcte'を使用する必要があります –
' set @ 1 = 1'とは何ですか?いくつかの言語拡張?スカラー定数? – wildplasser
@wildplasserが最後のクエリでは@ 1がパラメータになります。私はそれを賢明な例を作るために1に設定しました(または少なくとも試して) –