我是Oracle
的新手并且了解MS SQL
。我正在尝试根据user_id
中的Table2
获取电话号码,这是业务逻辑:
案例1:如果在Table1
中找到一个匹配项,则从Table2
案例2:如果在Table1
中找不到匹配项,则从Table2
案例3:如果在Table1
中找到多个匹配,那么对于所有assigned_care_levels
Care
,请Table2
按asc
排序desc
或ERROR: ORA-00907: missing right parenthesis
并选择顶行电话号码。
我编写了以下查询,当我单独运行它时,它可以正常工作。但是,当我使用if else语句进行cobine时,我收到以下错误if ((select count(distinct care_level) from Table1 where user_id = '100') > 0)
select phone from Table2 where care_level in (select distinct care_level from Table1 where user_id = '100')
and rownum = 1
order by care_level asc
else if((select count(distinct care_level) from Table1 where user_id = '100') = 0)
select phone from Table2 where care_level = 'default'
。这是我的代码:
{{1}}
答案 0 :(得分:0)
SET SERVEROUTPUT ON;
DECLARE
v_CARE_COUNT NUMBER := 0;
v_PHONE VARCHAr2(40) := NULL;
BEGIN
select count(distinct care_level)
into v_CARE_COUNT
from Table1
where user_id = '100';
IF(v_CARE_COUNT > 0) THEN
select phone into v_PHONE
from Table2
where care_level in
(select distinct care_level from Table1 where user_id = '100')
and rownum = 1;
ELSE
select phone into v_PHONE
from Table2
where care_level = 'default';
END IF;
DBMS_OUTPUT.PUT_LINE('PHONE is <'||v_PHONE||'>');
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Exception : '||SQLERRM);
END;
/
编辑:(AS SIngle SQL)
SELECT PHONE
FROM TABLE2
WHERE CARE_LEVEL in
(
SELECT CARE_LEVEL FROM TABLE1 WHERE USER_ID='100'
UNION
SELECT CARE_LEVEL FROM TABLE1 WHERE CARE_LEVEL='default'
AND NOT EXISTS
(SELECT 'X' FROM TABLE1 WHERE USER_ID='100')
)
AND ROWNUM = 1;
答案 1 :(得分:0)
'else if'语法错误。在Oracle中,您需要使用'ELSIF'并使用'END IF'完成整个条件语句。其中的SQL语句也应该跟一个;
尝试:
IF ((select count(distinct care_level) from Table1 where user_id = '100') > 0) THEN
select phone from Table2 where care_level in (select distinct care_level from Table1 where user_id = '100')
and rownum = 1
order by care_level asc;
ELSIF ((select count(distinct care_level) from Table1 where user_id = '100') = 0) THEN
select phone from Table2 where care_level = 'default'; END IF