我有一個user_config存盤代碼名稱和值的表。
例如,這樣的事情:
| ID | 代碼 | 價值 |
|---|---|---|
| 山姆 | 控制權 | 香港 |
| 山姆 | 電流 | 港元 |
| 山姆 | 山寨幣 | 歐元、美元 |
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 中分配變數?
uj5u.com熱心網友回復:
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';
資料庫小提琴
uj5u.com熱心網友回復:
@ekochergin 給出的答案具有未定義的行為,因為它使用變數合并進行聚合。相反,使用正常的條件聚合,然后分配給變數
select @country = MIN(case when u.code = 'ctr' then u.value end),
@currency = MIN(case when u.code = 'curr' then u.value end),
@alternate_currencies = MIN(case when u.code = 'altcurr' then u.value end)
from user_config u
where u.id = 'sam';
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/353890.html
標籤:sql sql-server
上一篇:搜索不同的表?
下一篇:如何使用正則運算式選擇分組依據
