【问题标题】:Assign sql query result to a macro variable in Python将sql查询结果分配给Python中的宏变量
【发布时间】:2017-07-19 13:54:24
【问题描述】:

我想将此查询的结果分配给一个变量,并将该变量用作另一个 sql 查询中的宏变量。

第一个查询:

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']

如果有人告诉我如何做到这一点,我将不胜感激?

谢谢!

【问题讨论】:

    标签: python sql macros


    【解决方案1】:

    只需将日期时间字符串格式化为以下格式的字符串:'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()
    

    【讨论】:

    • 你是想说什么吗?请发布错误(通常是回溯的最后几行)而不是代码。为什么不将光标对象用于execute()
    • hi- 当我运行第一个查询时,我得到这个错误: DatabaseError: (cx_Oracle.DatabaseError) ORA-01861: literal does not match format string [SQL: '\n select fis_week_id as start_wk \ n from date_dim\n where date_id = :sdate'] [参数:{'sdate': '2016-07-04'}]
    • 查看更新。对于 Oracle,您需要使用 to_date() 包装日期时间字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2022-01-06
    相关资源
    最近更新 更多