sql - 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 中分配变量?
解决方案
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';
推荐阅读
- c - 进程在 SIGINT 信号后死亡
- android - Google Drive API 注销
- html - DNN7 桌面模块不加载
- imagemagick - imagick导致输出解析错误
- python - Python - 读取熊猫列并将其转换为日期时间时的问题
- java - Spring Boot2 Oauth2 隐式流程 - http://localhost:8080/oauth/authorize 拒绝访问
- nginx - 如何在一个域名下托管多个应用程序?
- fortran - 在 Fedora Linux 上使用 gfortran 与 LAPACK 链接
- openrefine - 在 RDF 中导出项目
- javascript - 使用 AJAX DELETE 请求清除数组