首页 > 解决方案 > SQL Server:根据列值分配给不同的变量

问题描述

我有一个user_config存储代码名称和值的表。

例如,像这样:

ID 代码 价值
山姆 ctr 香港
山姆 当前 港币
山姆 altcurr 欧元、美元
declare
    @country varchar(2),
    @currency varchar(3),
    @alternate_currencies varchar(100);

select @country = u.value
from user_config u
where u.code = 'ctr'
  and u.id = 'sam';

select @currency = u.value
from user_config u
where u.code = 'curr'
  and u.id = 'sam';

select @alternate_currencies = u.value
from user_config u
where u.code = 'altcurr'
  and u.id = 'sam';

有没有办法根据代码的值在一个 SQL 中分配变量?

标签: sqlsql-server

解决方案


CASE 表达式将在这里为您提供帮助

select @country = (case when u.code = 'ctr' then u.value else @country end),
       @currency = (case when u.code = 'curr' then u.value else @currency end),
       @alternate_currencies = (case when u.code = 'altcurr' then u.value else @alternate_currencies end)
  from user_config u
 where u.id = 'sam';

小提琴手


推荐阅读