SQL select和case组合在一起

时间:2011-11-18 15:38:19

标签: sql oracle

我在选择语句时遇到问题而不确定我做错了什么。这是源表的结构:

  

源架构DATA1

     

来源表文件夹

     

来源列FOLDERID,USERID

     

目标架构DATA1

     

目的地表格FOLDER_USER

     

目标列FOLDER_ID,USER_ID

这是查询(我需要更改文件夹ID,因为它是从第一个查询中拉出来的情况因此):

DECLARE
BEGIN
   FOR FOLDER_ROW IN (SELECT FOLDERID = CASE 
                                WHEN FOLDERID = '10' THEN '1'
                                WHEN FOLDERID = '565' THEN '2'
                                WHEN FOLDERID = '11' THEN '3'
                                WHEN FOLDERID = '81' THEN '4'
                                ELSE '0'
                            END, USERID FROM DATA1.FOLDERS WHERE UPPER(OWNER) = 'ADMIN')
      LOOP                       
          INSERT INTO DATA1.FOLDER_USER (FOLDER_ID, CORP_ID) VALUES (FOLDER_ROW.FOLDERID, FOLDER_ROW.CORPID);
     END LOOP;
    COMMIT;
END;

当我执行时出现以下错误,我被困住了为什么我得到它。我知道它与select中的案例有关:

ORA-06550: line 3, column 39:
PL/SQL: ORA-00923: FROM keyword not found where expected
ORA-06550: line 3, column 22:
PL/SQL: SQL Statement ignored

4 个答案:

答案 0 :(得分:3)

SELECT FOLDERID = CASE错误。它应该是SELECT CASE ..... END作为FOLDERID

答案 1 :(得分:3)

看起来你只想要

BEGIN
   FOR FOLDER_ROW IN (SELECT CASE 
                                WHEN FOLDERID = '10' THEN '1'
                                WHEN FOLDERID = '565' THEN '2'
                                WHEN FOLDERID = '11' THEN '3'
                                WHEN FOLDERID = '81' THEN '4'
                                ELSE '0'
                            END folder_id, 
                            USERID 
                       FROM DATA1.FOLDERS 
                     WHERE UPPER(OWNER) = 'ADMIN')
      LOOP                       
          INSERT INTO DATA1.FOLDER_USER (FOLDER_ID, CORP_ID) VALUES (FOLDER_ROW.FOLDER_ID, FOLDER_ROW.CORPID);
     END LOOP;
    COMMIT;
END;

我在FOLDER_ID语句中添加了CASE的别名,并从FOLDERID =

中删除了CASE

答案 2 :(得分:1)

您也可以将其重写为decode (它不那么便携,而且阅读起来比较难)

DECLARE 
BEGIN    
    FOR folder_row IN (SELECT DECODE(folderid,'10', '1','565','2','11', '3','81', '4','0') AS folderid , 
                              userid 
                       FROM data1.folders 
                       WHERE UPPER(owner) = 'ADMIN')       
    LOOP                                  
        INSERT INTO data1.folder_user (folder_id, corp_id) VALUES (folder_row.folderid, folder_row.corpid);      
    END LOOP;     
    COMMIT; 
END; 

请参阅:http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/functions042.htm

答案 3 :(得分:1)

我不确定你是否在发布问题之前简化了你的代码,但我会完全摆脱CURSOR FOR循环,只使用带有子查询的INSERT语句。

我认为CURSOR FOR循环很好地被Oracle优化,所以它可能不会运行得更快但可能更容易理解。

BEGIN
  INSERT INTO DATA1.FOLDER_USER (FOLDER_ID, CORP_ID) 
  SELECT 
    CASE 
      WHEN FOLDERID = '10' THEN '1'
      WHEN FOLDERID = '565' THEN '2'
      WHEN FOLDERID = '11' THEN '3'
      WHEN FOLDERID = '81' THEN '4'
      ELSE '0'
    END folder_id, 
    USERID 
  FROM DATA1.FOLDERS 
  WHERE UPPER(OWNER) = 'ADMIN';

  COMMIT;
END;