2011-08-31 163 views
1

所以我有一個SQL查詢,給了我一個整數列表。這裏列出:從另一個查詢填充表

select distinct 
      re_entity_id 
     from cfo_transaction 
      inner join cfo_tran_quote ON tq_tr_transaction_id = tr_transaction_id 
      inner join cfo_trans_entity_rel on te_tr_transaction_id = tr_transaction_id and te_rv_rel_type_id in (713,715) 
      inner join com_entity on te_co_re_entity_id = re_entity_id 
     where 
      dbo.islmsloan(tq_tran_quote_id) = 1 
      and isnull(re_fictitious_bit,0) = 0 

這給了我一個id的列表,我需要插入另一個表與其他東西。其他表如下所示:

ens_engine_sponsor_id - PK 
ens_rs_sponsor_id - relates to the id from the other query 
ens_use_new_models_bit - should always be 1 for each insert 
ens_start_dt - should be 09/05/2011 for every one 
ens_end_dt - should be null for every one 

我怎麼會制定一些自動插入爲每個標識的一排在這個新表與給定的標準是什麼? (不是這樣的SQL好...)

感謝

+0

09/05/2011是5月9日還是9月5日? –

+0

9月5日...好的來電 – slandau

回答

3

您可以添加常數到您的SELECT列表如下。

insert into othertable 
      (ens_rs_sponsor_id, 
      ens_use_new_models_bit, 
      ens_start_dt) 
select distinct re_entity_id, 
       1, 
       '20110905' 
from cfo_transaction 
     inner join cfo_tran_quote 
     ON tq_tr_transaction_id = tr_transaction_id 
     inner join cfo_trans_entity_rel 
     on te_tr_transaction_id = tr_transaction_id 
      and te_rv_rel_type_id in (713, 715) 
     inner join com_entity 
     on te_co_re_entity_id = re_entity_id 
where dbo.islmsloan(tq_tran_quote_id) = 1 
     and isnull(re_fictitious_bit, 0) = 0 

如果使用DISTINCT的理由是消除帶來了由加入,你可以考慮使用WHERE EXISTS,而不是重複。

+0

謝謝。這看起來不錯 – slandau

1

你沒有提到ens_engine_sponsor_id是否是一個標識字段,但假設它是那麼你可以做到這一點。

INSERT INTO MyTableName(
     ens_rs_sponsor_id,  
     ens_use_new_models_bit, 
     ens_start_dt, 
     ens_end_dt) 
select distinct 
      re_entity_id, 
      1, 
      '09 May 2011', 
      NULL 
     from cfo_transaction 
      inner join cfo_tran_quote ON tq_tr_transaction_id = tr_transaction_id 
      inner join cfo_trans_entity_rel on te_tr_transaction_id = tr_transaction_id and te_rv_rel_type_id in (713,715) 
      inner join com_entity on te_co_re_entity_id = re_entity_id 
     where 
      dbo.islmsloan(tq_tran_quote_id) = 1 
      and isnull(re_fictitious_bit,0) = 0