Why EXECUTE IMMEDIATE is needed here?

后端 未结 3 1549
自闭症患者
自闭症患者 2020-12-18 10:52

I am a SQL Server user and I have a small project to do using Oracle, so I’m trying to understand some of the particularities of Oracle and I reckon that I need some help to

3条回答
  •  没有蜡笔的小新
    2020-12-18 11:03

    I have modified your code a litle bit and it works as far as logic is concerned. But as exp[lained in earlier posts creating GTT on the fly at run time is not at all is a goood idea.

    --- Firstly by dropping the table i.e NO TABLE EXISTS in the DB in AVROY 
    
    SET serveroutput ON;
    DECLARE
      table_count INTEGER;
      var_sql     VARCHAR2(1000) := 'create GLOBAL TEMPORARY table TEST (            
    hello varchar(1000) NOT NULL)';
    BEGIN
    
    EXECUTE IMMEDIATE 'DROP TABLE AVROY.TEST'; --Added the line just to drop the table as per your comments
    
      SELECT COUNT(*)
      INTO table_count
      FROM all_tables
      WHERE table_name = 'TEST'
      AND OWNER        = 'AVROY';
      IF table_count   = 0 THEN
        EXECUTE IMMEDIATE var_sql;
        dbms_output.put_line('table created');
      ELSE
        INSERT INTO AVROY.test
          (hello
          ) VALUES
          ('hi'
          );
      END IF;
    END;
    
    --------------------OUTPUT-----------------------------------------------
    
    anonymous block completed
    table created
    
    SELECT COUNT(*)
    --  INTO table_count
      FROM all_tables
      WHERE table_name = 'TEST'
      AND OWNER        = 'AVROY';
    
    COUNT(*)
    ------
    1
    --------
    
    -- Second option is without DROPPING TABLE
    
    
    SET serveroutput ON;
    DECLARE
      table_count INTEGER;
      var_sql     VARCHAR2(1000) := 'create GLOBAL TEMPORARY table TEST (            
    hello varchar(1000) NOT NULL)';
    BEGIN
    
    --EXECUTE IMMEDIATE 'DROP TABLE AVROY.TEST';
    
      SELECT COUNT(*)
      INTO table_count
      FROM all_tables
      WHERE table_name = 'TEST'
      AND OWNER        = 'AVROY';
      IF table_count   = 0 THEN
        EXECUTE IMMEDIATE var_sql;
        dbms_output.put_line('table created');
      ELSE
        INSERT INTO AVROY.test
          (hello
          ) VALUES
          ('hi'
          );
          dbms_output.put_line(SQL%ROWCOUNT||' Rows inserted into the table');
      END IF;
    END;
    
    -------------------------------OUTPUT-------------------------------------
    
    anonymous block completed
    1 Rows inserted into the table
    
    
    ---------------------------------------------------------------------------
    

提交回复
热议问题