使用临时表

时间:2017-02-21 12:08:27

标签: sql sql-server tsql

我有以下查询填充临时表:

with CTE as
(
select a.accountid as 'myid',
       a.new_mprnnumber, 
       a.new_customernumber,
       b.*, 
       row_number() 
         over (partition by new_customernumber -- add additional partitions as you would group bys
               order by billingPeriodEndDate desc) as r_ord 
from [CRM].[crm4_MSCRM].[dbo].[AccountExtensionBase] a
inner join bill  b
  on a.new_mprnnumber = b.MPRN
where new_accountstage = 7
and new_accounttype = 2 
)
select *
into #tempCTE
from CTE
where r_ord = 1

在临时表中收集信息后,我想迭代每条记录并使用accountid更新主表,但使用以下语句:

update [CRM].[crm4_MSCRM].[dbo].[AccountExtensionBase]
set new_invoicenumber = invoicenumber
where accountid = #tempCTE.myid

我收到的错误是多部分标识符无法绑定,是否有任何关于导致此问题的原因?

1 个答案:

答案 0 :(得分:1)

您需要引入临时表:

update aeb
    set new_invoicenumber = t.invoicenumber
    from [CRM].[crm4_MSCRM].[dbo].[AccountExtensionBase] aeb join
         #tempCTE t
         on aeb.accountid = t.myid;

作为备注,您不需要临时表。你可以这样做:

with tempCTE as ( . . . )
update aeb
    set new_invoicenumber = t.invoicenumber
    from [CRM].[crm4_MSCRM].[dbo].[AccountExtensionBase] aeb join
         tempCTE t
         on aeb.accountid = t.myid
    where tempCTE.r_ord = 1