简体   繁体   中英

Python+SQL: How to execute a procedure from python? [NOT CALLING the stored procedure]

I am trying to get count of rows from list of tables where all the table's column should have Col_year = 1994.

It this is possible in sql with out writing loop in python, as it would need lots DB hit.

To do this, I have written a proc like below:

DECLARE
  l_counter NUMBER;
  tot_counter NUMBER;
  v_sql varchar2(10000);
  cursor c1 is 
    select table_name from ALL_TABLES
    where table_name in  ("Table1", "Table2", "Table3");

BEGIN
    tot_counter := 0;
  FOR rec IN c1 LOOP
    v_sql := 'select count(*) from '|| rec.table_name ||' where Col_year = 1994';
    EXECUTE IMMEDIATE v_sql INTO l_counter;
    tot_counter := tot_counter +  l_counter;
    DBMS_OUTPUT.PUT_LINE(rec.table_name || ' l_counter ' || l_counter || ' tot_counter ' || tot_counter);

  END LOOP;
END;

How to invoke this from python?

Situation is that I cannot create this in the actual Database, as this is just temporary purpose. Hence, I am looking something like cursor.executeproc() insteat of cursor.callproc()? Is this possible?

First, you don't need a procedure a single SQL query can do it :

SQL Fiddle

Oracle 11g R2 Schema Setup :

Query 1 :

SELECT SUM(c) 
FROM (
    SELECT COUNT(*) c FROM Table1 WHERE Col_year = 1999
    Union all
    SELECT COUNT(*) c FROM Table2 WHERE Col_year = 1999
    Union all
    SELECT COUNT(*) c FROM Table3 WHERE Col_year = 1999
)

Results :

| SUM(C) |
|--------|
|     10 |

Second, here is some link that may help you on your answer :

Return variable from cx_Oracle PL/SQL call in Python

cx_Oracle and output variables

And how to do it (I can't test it)

cursor = connection.cursor()
lOutput = cursor.var(cx_Oracle.STRING)
cursor.execute("""
            DECLARE
              l_counter NUMBER;
              tot_counter NUMBER;
              v_sql varchar2(10000);
              cursor c1 is 
                select table_name from ALL_TABLES
                where table_name in  (Table1, Table2, Table3);

            BEGIN
                tot_counter := 0;
              FOR rec IN c1 LOOP
                v_sql := 'select count(*) from '|| rec.table_name ||' where Col_year = 1994';
                EXECUTE IMMEDIATE v_sql INTO l_counter;
                tot_counter := tot_counter +  l_counter;
                DBMS_OUTPUT.PUT_LINE(rec.table_name || ' l_counter ' || l_counter || ' tot_counter ' || tot_counter);

              END LOOP;
            END;
            """)
print lOutput

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM