我正在从cte更新但是遇到了这个常见错误
The multi-part identifier "t.newfips" could not be bound.
我知道在其他情况下如何处理此错误,但在这种情况下我不知道如何处理。
我的查询
with t as (
select * from FIPSModificationsBEA t1
inner join [BEAtoFIPS] t2
on cast(t1.newfips as varchar) = concat(t2.statefips,t2.CountyFIPS)
)
update [BEAtoFIPS]
set statefips = left(t.oldfips, 2) , countyfips = right(t.oldfips, 3)
from [BEAtoFIPS] t2
where concat(t2.statefips, t2.countyfips) = t.newfips
go
我通过以下查询检查了查询
with t as (
select * from FIPSModificationsBEA t1
inner join [BEAtoFIPS] t2
on cast(t1.newfips as varchar) = concat(t2.statefips,t2.CountyFIPS)
)
select newfips from t
go
此查询有效。因此,我很困惑。为什么后一个有效,但前一个没有?它们在结构上是否基本相同?前者出了什么问题?
答案 0 :(得分:1)
您只需更新cte:
即可with t as (
select * from FIPSModificationsBEA t1
inner join [BEAtoFIPS] t2
on cast(t1.newfips as varchar) = concat(t2.statefips,t2.CountyFIPS)
)
update t
set statefips = left(t.oldfips, 2) , countyfips = right(t.oldfips, 3)
go
否则加入cte
with t as (
select * from FIPSModificationsBEA t1
inner join [BEAtoFIPS] t2
on cast(t1.newfips as varchar) = concat(t2.statefips,t2.CountyFIPS)
)
update t2
set statefips = left(t.oldfips, 2) , countyfips = right(t.oldfips, 3)
from [BEAtoFIPS] t2
inner join t
on concat(t2.statefips, t2.countyfips) = t.newfips
go
答案 1 :(得分:1)
您的UPDATE
查询没有CTE FROM
的{{1}}条目(但您的t
会这样做,这就是它运作的原因)。
考虑CTE的一种方法就像只能查看一个查询的临时视图。所以你有这样的(有点像):
SELECT
在此示例中可能更明显的是Create View t (...)
as
(
select * from FIPSModificationsBEA t1
inner join [BEAtoFIPS] t2
on cast(t1.newfips as varchar) = concat(t2.statefips,t2.CountyFIPS)
)
go
update [BEAtoFIPS]
set statefips = left(t.oldfips, 2) , countyfips = right(t.oldfips, 3)
from [BEAtoFIPS] t2
where concat(t2.statefips, t2.countyfips) = t.newfips
go
实际上并未在t
查询中的任何位置定义{。}}。
要解决此问题,您需要UPDATE
到视图,告诉它如何连接到查询:
JOIN
CTE的查询需要与CTE完全相同 - update [BEAtoFIPS]
set statefips = left(t.oldfips, 2) , countyfips = right(t.oldfips, 3)
from [BEAtoFIPS] t2
join t
on concat(t2.statefips, t2.countyfips) = t.newfips
go
并指定它与查询其余部分的关系。
答案 2 :(得分:1)
您尚未在更新查询中加入CTE,因此t
尚未分配。
试试这个:
WITH tempData AS (
SELECT * FROM FIPSModificationsBEA t1
INNER JOIN [BEAtoFIPS] t2
ON CAST(t1.newfips as varchar) = CONCAT(t2.statefips,t2.CountyFIPS)
)
UPDATE t2
SET statefips = LEFT(t.oldfips, 2),
countyfips = right(t.oldfips, 3)
FROM [BEAtoFIPS] AS t2
INNER JOIN tempData AS t
ON t.newFips = concat(t2.statefips, t2.countyfips)
但是你应该能够在没有cte的情况下做到这一点:
UPDATE b
SET statefips = LEFT(m.oldfips, 2),
countyfips = RIGHT(m.oldfips, 3)
FROM [BEAtoFIPS] AS b
INNER JOIN FIPSModificationsBEA AS m
ON CAST(m.newfips as varchar) = CONCAT(b.statefips,b.CountyFIPS)