PLSQL dynamic query

后端 未结 2 882
小蘑菇
小蘑菇 2021-01-15 06:01

I have a table A which has column A which holds table names as values. All these tables have a common column C. I need maximum value of this column

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-15 06:20

    There is some miss match in veriables that you had used i.e.

    1. declared as "c_table" but accessing as "c_table2"
    2. Each table common column name is "C" but accessing as "object_ref"
    3. In dynamic query use INTO keyword to store the value to your varibale

    Suggestions

    1. Use concat() function to prepare the query dynamically i.e. something like:

      SET @SQL := CONCAT('SELECT max(c) INTO ', c_obj, ' FROM ',c_table);

    2. Steps of implementing dynamic query is:

      SET @SQL = 
      PREPARE stmt FROM @SQL;
      EXECUTE stmt;
      

    Sample code:

    DECLARE    
     query1 VARCHAR2(100);
     c_table VARCHAR2(40);
     c_obj VARCHAR2(20);
     CURSOR cursor_a IS
     SELECT a FROM A;  
    BEGIN
    OPEN cursor_a;
       LOOP
          FETCH cursor_a INTO c_table;      
          EXIT WHEN cursor_a%notfound; 
          SET @SQL := CONCAT('SELECT max(object_ref) AS c_obj INTO ', c_obj, ' FROM ',c_table);
        PREPARE stmt FROM @SQL;         
        EXECUTE stmt;    
        dbms_output.put_line('Maximum value: '|| c_table || c_obj);
       END LOOP;
    CLOSE cursor_a;
    END;
    

提交回复
热议问题