1

私は に不慣れOracleで、知識がありMS SQLます。差出人に応じて電話番号を取得しようとしてuser_idTable2ますが、ビジネスロジックは次のとおりです。

  • ケース 1: で 1 つの一致が見つかった場合は、Table1それぞれのフリーダイヤル番号を取得します。Table2

  • ケース 2: で一致するものが見つからない場合はTable1、デフォルトのフリーダイヤル番号を取得します。Table2

  • ケース 3: 複数の一致が見つかった場合、Table1それらすべてについて、 ordered byまたはから値をassigned_care_levels取得し、一番上の行の電話番号を選択します。CareTable2ascdesc

個別に実行すると正常に動作する次のクエリを作成しました。ただし、 if else ステートメントを使用して結合すると、次のエラーが発生しますERROR: ORA-00907: missing right parenthesis。これが私のコードです:

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'
4

2 に答える 2

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;
 /

編集:(単一の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;
于 2013-12-20T22:05:59.537 に答える
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
于 2013-12-20T22:23:13.967 に答える