2017-07-19 170 views
0

我想將此查詢的結果分配給變量,並將該變量用作另一個SQL查詢中的宏變量。將SQL查詢結果分配給Python中的宏變量

第一次查詢:

start_week = 201619 

start_date=connection.execute(""" 
select min(CAST(date_id as DATE)) as start_date from date_table 
where CAST(week_id as INT) = %d 
""" 
%(start_week)) 

start_date = start_date.fetchone() 

此查詢的結果是:(datetime.datetime(2017年,7,2,0,0))

第二查詢:現在我想用這是第二個查詢宏變量

start_wk=connection.execute(""" 
select fis_week_id as start_wk from date_dim 
where date_id = %s 
""" 
%(start_date)) 

不過,我得到一個錯誤,如:

DatabaseError: (cx_Oracle.DatabaseError) ORA-00936: missing expression 
[SQL: '\nselect week_id as start_wk from date_dim\nwhere date_id = (datetime.datetime(2016, 7, 4, 0, 0),)\n'] 

如果有人告訴我如何做到這一點,我將不勝感激。

謝謝!

回答

0

只需字符串將日期時間格式化爲字符串格式:'YYYY-M-D'其中RDBMS將其讀取爲日期時間。此外,將該日期作爲參數傳遞,不插入到SQL字符串中。見Oracle+Python最佳實踐:

str_start_date = datetime.datetime.strftime(start_date[0], '%Y-%m-%d') 

cur = connection.cursor() 

start_wk = cur.execute(""" 
    select fis_week_id as start_wk 
    from date_dim 
    where date_id = to_date(:sdate, 'yyyy-mm-dd')""", {'sdate':str_start_date}) 

cur.close() 

然而,考慮而不需要中間變量,其中第一個查詢成爲第二個查詢的WHERE子句中的子查詢的兩種查詢相結合:

cur = connection.cursor() 

start_wk = cur.execute(""" 
    select fis_week_id as start_wk 
    from date_dim 
    where date_id = (select min(CAST(date_id as DATE)) as start_date 
        from date_table 
        where CAST(week_id as INT) = :sweek)""", {'sweek':start_week}) 
cur.close() 
+0

你想說些什麼呢?請發佈錯誤(通常是回溯的最後一行)而不是代碼。爲什麼你不使用遊標對象來執行'execute()'? – Parfait

+0

hi-當我運行第一個查詢,我得到這個錯誤:DatabaseError:(cx_Oracle.DatabaseError)ORA-01861:文字不匹配格式字符串 [SQL:'\ n從date_dim選擇fis_week_id作爲start_wk \ n \ n date_id =:sdate'] [參數:{'sdate':'2016-07-04'}] –

+0

查看更新。對於Oracle,你需要用'to_date()'來包裝日期時間字符串。 – Parfait

相關問題