2016-06-18 17 views
0

大きなSQLクエリの一部として、別の(一時的な)テーブルから関連アイテムを格納するための一時テーブルを作成しています。 insertステートメントのselect部分は、CASEステートメントを使用して、dataSource列の値に基づいて、最終列(labSample)に1または0のいずれかを入力します。 SSMSは無効な列を返します。dataSourceへの参照はlabSample列です。私は私の人生のために、なぜこのエラーが発生しているのかを考え出すことはできません。これは構文エラーですか、何か不足していますか?以下で使用SQL Server 2008のCASEステートメントで無効な列エラーが発生する

命名規則は、列名の前に下線で下線なしの列名は、(#related表に過ぎずdataSourcelabSample列を除く)#temp_traceテーブルに由来しながら、#relatedテーブルに新しい列です。

私は本当にこの1つの助けに感謝します!

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のエイリアスです。以下のようにケースを変更する必要があります。

+0

ありがとう@マヘディ。魅力のように働いた。私は '' dataSource'をすでに '#related'テーブルのカラムとして宣言しているので、case文の中からアクセスすることができますが、明らかに間違っていました。 –

0

次のように変更する必要があります。それはあなたを助けるかもしれない

CASE WHEN kd.kld_value_s = 'Field' THEN 0 
     WHEN kd.kld_value_s = 'Unknown' THEN 0 
     ELSE 1 
END AS dataSource 
関連する問題