2016-06-18 201 views
0

作爲較大的SQL查詢的一部分,我創建了一個臨時表來存儲來自另一個(臨時)表的相關項目。 insert語句的select部分使用CASE語句來填充最後一列(labSample),其中基於dataSource列的值爲1或0。 SSMS在labSample列中返回無效列錯誤,以引用dataSource。我不能爲我的生活找出這個錯誤發生的原因 - 這是一個語法錯誤還是我錯過了什麼?SQL Server 2008 CASE語句提供了無效的列錯誤

以下使用的命名規則是列名前述下劃線處於#related表中的新列,同時沒有下劃線的列名在#temp_trace表起源(除了dataSourcelabSample列,其僅在#related表)。

我真的很感謝這個幫助!

create table #related (_tr_id int, _mp_id int, _sta_id int, _tr_number_s nvarchar(20), 
    _tr_tstamp_ts datetime, _tr_team_s nvarchar(100), _tr_comment_s nvarchar(512), 
    _kld_id_medium int, _kld_id_reason int, _kld_id_typeofsmpl int, _sp_id int, 
    _sa_id int, _sa_depth_fl float, _fr_number_l int, dataSource nvarchar(128), labSample bit) 

insert into #related (_tr_id, _mp_id, _sta_id, _tr_number_s, 
    _tr_tstamp_ts, _tr_team_s, _tr_comment_s, 
    _kld_id_medium, _kld_id_reason, _kld_id_typeofsmpl, _sp_id, _sa_id, _sa_depth_fl, 
    _fr_number_l, dataSource, labSample) 
select 
    tt.tr_id as _tr_id, 
    tt.mp_id as _mp_id, 
    tt.sta_id as _sta_id, 
    tt.tr_number_s as _tr_number_s, 
    tt.tr_tstamp_ts as _tr_tstamp_ts, 
    tt.tr_team_s as _tr_team_s, 
    tt.tr_comment_s as _tr_comment_s, 
    tt.kld_id_medium as _kld_id_medium, 
    tt.kld_id_reason as _kld_id_reason, 
    tt.kld_id_typeofsmpl as _kld_id_typeofsmpl, 
    sp.sp_id as _sp_id, 
    sa.sa_id as _sa_id, 
    sa.sa_depth_fl as _sa_depth_fl, 
    fr.fr_number_l as _fr_number_l, 
    kd.kld_value_s as dataSource, 
    case dataSource 
     when 'Field' then 0 
     when 'Unknown' then 0 
     else 1 
    end 
from #temp_trace tt 
    inner join spot sp on sp.tr_id = tt.tr_id 
    inner join sample sa on sa.sp_id = sp.sp_id 
    inner join fraction fr on fr.sa_id = sa.sa_id 
    inner join kld_data kd on kd.kld_id = fr.kld_id_datasource 
where mp_id = @tr_mp_id and 
    sta_id = @tr_sta_id and 
    CAST(tr_tstamp_ts as DATE) = CAST(@tr_tstamp_ts as DATE) 

回答

2

據我所知,dataSource不是任何連接表中的列名稱。它實際上是kd.kld_value_s的別名。你需要改變你的情況,如下所示:

case kd.kld_value_s 
    when 'Field' then 0 
    when 'Unknown' then 0 
    else 1 
end 
+0

謝謝@Mahedi。像魅力一樣工作。我認爲,因爲我已經在'#related'表中聲明瞭'dataSource'作爲列,所以我可以從case語句中訪問它,但顯然我錯了! –

0

嘗試follwing。它可能會幫助你

CASE WHEN kd.kld_value_s = 'Field' THEN 0 
     WHEN kd.kld_value_s = 'Unknown' THEN 0 
     ELSE 1 
END AS dataSource