如何使用 CTE 基于层次结构插入多条记录
How to use a CTE to insert multiple records based on hierarchy
假设我有一个 Customer
table,其中包含 CustomerId
作为主键和 ParentCustomerId
作为外键,我想将插入语句级联到为层次结构链中的每个客户创建一条记录。
我还有一个 CustomerContact table,它的集群主键为 CustomerId
、PersonId
和 DateCreated
所以如果我有以下内容:
客户 1:CustomerId: 1
:ParentCustomerId: Null
客户 2:CustomerId: 2
:ParentCustomerId: 1
客户 3:CustomerId: 3
:ParentCustomerId: 2
然后我将 1
传递到我的客户 ID 中,但我想创建 3(尽管在本例中 3 是一个变量,层次结构可以更深)以便我插入到不同的 table 链中每个客户一行。
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 来获取与参数 @1
相关的所有客户的子级并在 CustomerContact
中为每个子级创建一条记录?
您需要使用 recursive common table expression
使用 union all
。这是一个简化的例子:
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
使用您的示例数据,这将 return 3 条记录,还可以处理更深层次的关系。
假设我有一个 Customer
table,其中包含 CustomerId
作为主键和 ParentCustomerId
作为外键,我想将插入语句级联到为层次结构链中的每个客户创建一条记录。
我还有一个 CustomerContact table,它的集群主键为 CustomerId
、PersonId
和 DateCreated
所以如果我有以下内容:
客户 1:CustomerId: 1
:ParentCustomerId: Null
客户 2:CustomerId: 2
:ParentCustomerId: 1
客户 3:CustomerId: 3
:ParentCustomerId: 2
然后我将 1
传递到我的客户 ID 中,但我想创建 3(尽管在本例中 3 是一个变量,层次结构可以更深)以便我插入到不同的 table 链中每个客户一行。
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 来获取与参数 @1
相关的所有客户的子级并在 CustomerContact
中为每个子级创建一条记录?
您需要使用 recursive common table expression
使用 union all
。这是一个简化的例子:
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
使用您的示例数据,这将 return 3 条记录,还可以处理更深层次的关系。