2017-10-12 47 views
2

我想從所有表格列應該有Col_year = 1994的表列表中計算行數。Python + SQL:如何從python執行程序? [NOT CALLING the stored procedure]

這是在sql中可能的,它會需要很多數據庫命中。

要做到這一點,我已經寫了PROC象下面這樣:

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; 

如何從蟒蛇調用此?

情況是我無法在實際的數據庫中創建它,因爲這只是暫時的目的。因此,我看起來像cursor.ccuteproc()的cursor.executeproc()?這可能嗎?

+0

您應該添加使用的數據庫,版本和適配器。 –

+0

這個想法是動態執行一個過程...腳本是python代碼的一部分。因此,我想在數據庫中創建此過程。 – neoman1

回答

1

首先,你並不需要一個過程一個SQL查詢可以做到這一點:

SQL Fiddle

的Oracle 11g R2架構設置

查詢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 | 

其次,這裏是一些鏈接,可以幫助你在你的答案:

Return variable from cx_Oracle PL/SQL call in Python

cx_Oracle and output variables

而如何做到這一點(我可以」 t測試)

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