Sql 使用临时表找不到多部分标识符

Sql 使用临时表找不到多部分标识符,sql,sql-server,tsql,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

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

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
update aeb
    set new_invoicenumber = t.invoicenumber
    from [CRM].[crm4_MSCRM].[dbo].[AccountExtensionBase] aeb join
         #tempCTE t
         on aeb.accountid = t.myid;
在临时表中收集信息后,我希望遍历每条记录,并使用accountid(但使用以下语句)更新主表:

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

我收到一个错误,无法绑定多部分标识符,您知道是什么导致了这个问题吗?

您需要引入临时表:

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
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

你能从CTE执行select吗?用你正在使用的数据库(大概是SQL Server)标记你的问题。你到底为什么要遍历记录?这是在数据库中几乎不应该做的事情。您已经在CTE中识别了最新的记录。因为花了太长时间,我只是检查它是否在做同样的事情,更新4163帐户花费了13:10分钟。我是否将我的r_ord=1对账单留在那里?我只想用最新的发票更新发票号,列表应该返回accountid,然后我想将其用作update的键yes将r_ord=1作为update语句中的where子句。