2017-06-20 78 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来生成使用某些智能公式的语句时的情况。我已经使用了一些巨大的代码。