我正在尝试使用if else案例基于两个选择条件加入数据。 我有一个汇率表(dbo.DATA_EXCHANGE_RATE),一个有年(dbo.DATA_EXCHANGE_RATE.YEAR_OBJ_REF),另一个有货币(dbo.DATA_EXCHANGE_RATE.CURRECY_OBJ_REF)。如果货币是欧元,我想仅根据货币选择我的汇率,否则根据年份和货币。我拥有的是
select dbo.DATA_EXCHANGE_RATE.EXCHANGE_RATE_CAPTION
from dbo.DATA_EXCHANGE_RATE
inner join dbo.measures
on(CASE WHEN dbo.measures.CURRECY_OBJ_REF =
(select DATA_ID from dbo.DATA_CURRENCY where CURRENCY_CAPTION = 'T-EUR')
THEN
dbo.DATA_EXCHANGE_RATE.CURRECY_OBJ_REF = dbo.measures.CURRECY_OBJ_REF
ELSE
dbo.DATA_EXCHANGE_RATE.YEAR_OBJ_REF = dbo.measures.YEAR_OBJ_REF
and dbo.DATA_EXCHANGE_RATE.CURRECY_OBJ_REF = dbo.measures.CURRECY_OBJ_REF
END)
但这会引发错误:
Failed!
Incorrect syntax near '='
答案 0 :(得分:1)
我认为以下查询维护您的预期逻辑,减去语法错误:
SELECT dbo.DATA_EXCHANGE_RATE.EXCHANGE_RATE_CAPTION
FROM dbo.DATA_EXCHANGE_RATE t1
INNER JOIN dbo.measures t2
ON
(
dbo.measures.CURRECY_OBJ_REF = (select DATA_ID from dbo.DATA_CURRENCY
where CURRENCY_CAPTION = 'T-EUR') AND
t1.CURRECY_OBJ_REF = t2.CURRECY_OBJ_REF
)
OR
(
dbo.measures.CURRECY_OBJ_REF <> (select DATA_ID from dbo.DATA_CURRENCY
where CURRENCY_CAPTION = 'T-EUR') AND
t1.YEAR_OBJ_REF = t2.YEAR_OBJ_REF AND
t1.CURRECY_OBJ_REF = t2.CURRECY_OBJ_REF
)
我不喜欢将子查询放入ON
子句,因为它感觉很奇怪。我怀疑如果我们要查看您的数据,我们可能会改进此查询。
答案 1 :(得分:1)
CASE
在过程语言中不像if
那样工作,它返回一个原子值。它不能以这种方式用于程序流程。您想要的是AND
和OR
:
select DER.EXCHANGE_RATE_CAPTION
FROM dbo.DATA_EXCHANGE_RATE DER
inner join dbo.measures M
ON (
M.CURRECY_OBJ_REF = (SELECT DATA_ID from dbo.DATA_CURRENCY where CURRENCY_CAPTION = 'T-EUR')
AND DER.CURRECY_OBJ_REF = M.CURRECY_OBJ_REF
)
OR (
M.CURRECY_OBJ_REF <> (SELECT DATA_ID from dbo.DATA_CURRENCY where CURRENCY_CAPTION = 'T-EUR')
AND DER.YEAR_OBJ_REF = M.YEAR_OBJ_REF
AND DER.CURRECY_OBJ_REF = M.CURRECY_OBJ_REF
)
我还使用了别名来提高可读性。
答案 2 :(得分:0)
Declare @Query as nvarchar(max) = 'select dbo.DATA_EXCHANGE_RATE.EXCHANGE_RATE_CAPTION
from dbo.DATA_EXCHANGE_RATE
inner join dbo.measures
on (CASE WHEN dbo.measures.CURRECY_OBJ_REF =(select DATA_ID from dbo.DATA_CURRENCY where CURRENCY_CAPTION = ''T-EUR'')
THEN
dbo.DATA_EXCHANGE_RATE.CURRECY_OBJ_REF = dbo.measures.CURRECY_OBJ_REF
ELSE
dbo.DATA_EXCHANGE_RATE.YEAR_OBJ_REF = dbo.measures.YEAR_OBJ_REF
and dbo.DATA_EXCHANGE_RATE.CURRECY_OBJ_REF = dbo.measures.CURRECY_OBJ_REF
END)'
EXEC SP_EXECUTESQL @Query
&#13;
答案 3 :(得分:0)
将其替换为OR表达式
declare @EURO int;
select @EURO = DATA_ID from dbo.DATA_CURRENCY where CURRENCY_CAPTION = 'T-EUR';
select dbo.DATA_EXCHANGE_RATE.EXCHANGE_RATE_CAPTION
from dbo.DATA_EXCHANGE_RATE
inner join dbo.measures on (dbo.measures.CURRECY_OBJ_REF = @EURO and dbo.DATA_EXCHANGE_RATE.CURRECY_OBJ_REF = dbo.measures.CURRECY_OBJ_REF) or
(dbo.measures.CURRECY_OBJ_REF <> @EURO and dbo.DATA_EXCHANGE_RATE.YEAR_OBJ_REF = dbo.measures.YEAR_OBJ_REF and dbo.DATA_EXCHANGE_RATE.CURRECY_OBJ_REF = dbo.measures.CURRECY_OBJ_REF);