2017-06-20 72 views
0

我有幾個硬編碼的case語句(case when ID in ('1','2', etc) then X)。有沒有辦法將其顯示爲table其中ID值1,2對應於描述X?case statement values to表

然後做一個參考表。

否則我需要手動將這些值插入到該表中。所以最終,我想在查詢中使用與該表的連接,而不是case語句。

+0

使用[表值構造函數](https://docs.microsoft.com/en-us/sql/t-sql/queries/table-value-constructor-transact-sql)。 –

+0

是的,您可以使用列ID,描述和用例語句創建表格,將行插入第二列 –

+0

我的想法是,如果有任何「智能」的方式來實現這一點。如果我必須手動添加所有Id或寫入/更改很多,則沒有任何理由避免手動插入所有值 – Proffesore

回答

0

用這種方式,如果它適合你

create table #temp 
(id int, description Varchar(55)) 
insert into #temp (id) 
values (1); 
insert into #temp (id) 
values (2); 
insert into #temp (id) 
values (1); 
insert into #temp (id) 
values (3); 

update #temp 
set description = 'first' where id in (1,2) 
; 
update #temp 
set description = 'Second' where id = 3 

select * from #temp 

drop table #temp 
1

您可以在查詢中創建一個參考表:

with ref as (
     select v.id, v.val 
     from (values ('1', 'x'), 
        ('2', 'x'), 
        . . . 
      ) v(id, val) 
    ) 
select . . . 
from t join 
    ref 
    on t.id = ref.id; 

您也可以在值存儲在一個臨時表,全局臨時表或永久表。

0

通常,一個快速解決方法是使用excel來生成使用某些智能公式的語句時的情況。我已經使用了一些巨大的代碼。