无法选择临时表的列?

时间:2017-01-06 13:31:14

标签: sql-server temp-tables

似乎我无法通过从我选择的视图中继承的列名来选择临时表的列。我收到错误:“Msg 207,Level 16,State 1,Procedure GetConsolidatedData,Line 44 [Batch Start Line 0] 列名称'comp_id'无效。“

select * 
into #tmp0
from Competitor_View
where [Competitor Name] like @competitor_name;

select * 
into #tmp1
from #tmp0
where [Competitor Part Number] like @competitor_part;

select * 
into #CustomerResult
from #tmp1
where [Koyo Part Number] like @koyo_part;

--------------

select * 
into #tmp3
from Customer_View
where [Customer Name] like @customer_name;

select * 
into #tmp4
from #tmp3
where [Customer Part Number] like @customer_part;

select * 
into #CompetitorResult
from #tmp4
where [Koyo Part Number] like @koyo_part;

--everything after this fails
select 
#CompetitorResult.comp_id,
#CompetitorResult.[Competitor Part Number], 
#CompetitorResult.[Competitor Comment], 
#CompetitorResult.[Competitor Name], 
#CompetitorResult.[Koyo Part Number] as [Associated Koyo Part Number],
#CustomerResult.cust_id, 
#CustomerResult.[Customer Part Number], 
#CustomerResult.[Customer Comment], 
#CustomerResult.[Customer Name] 
from #CompetitorResult
join #CustomerResult
on #CompetitorResult.[Koyo Part Number] = #CustomerResult.[Koyo Part Number];

我知道我的列名正确,因为运行以下内容可以确认:

SELECT  *
FROM    tempdb.sys.columns 
WHERE object_id = OBJECT_ID('tempdb..#CompetitorResult')

1 个答案:

答案 0 :(得分:2)

您的查询应该看起来像这样......(没有任何临时表)

select  cp.comp_id
       ,cp.[Competitor Part Number]
       ,cp.[Competitor Comment]
       ,cp.[Competitor Name]
       ,cp.[Koyo Part Number] as [Associated Koyo Part Number]
       ,cu.cust_id
       ,cu.[Customer Part Number]
       ,cu.[Customer Comment]
       ,cu.[Customer Name] 
from Competitor_View cp
INNER JOIN Customer_View cu ON cp.[Koyo Part Number] = cu.[Koyo Part Number]
where cp.[Koyo Part Number] like @koyo_part
  AND cp.[Competitor Part Number] like @competitor_part
  AND cp.[Competitor Name] like @competitor_name
  AND cu.[Customer Name] like @customer_name
  AND cu.[Customer Part Number] like @customer_part
  AND cu.[Koyo Part Number] like @koyo_part