【问题标题】:Declare a variable in oracle in a python SQL query在 Python SQL 查询中在 oracle 中声明一个变量
【发布时间】:2021-01-29 19:24:26
【问题描述】:

我正在将代码从 SQL Server 移植到 Oracle。

DECLARE @DispatchCount int,
@HeadCount int;

SELECT @DispatchCount = (
    select 200 -- business query would replace sample
);

select @HeadCount = (
    select 50 -- business query would replace sample 
);

select @DispatchCount / @HeadCount;

我尝试了 oracle 声明语法。

DECLARE
    head_count INTEGER;

BEGIN

select 100 as DUMMY into head_count from dual;
dbms_output.put_line(head_count);

END;

我正在从 cx_oracle 查询 Python 中的只读 oracle 11g 数据库:

cursor.execute(sql)
rows = cursor.fetchall()

这会在 fetchall 语句中引发错误:'not a query'。 有没有办法在 oracle 中声明可以在 SQL 查询中使用的变量?

【问题讨论】:

  • 我看到了各种各样的答案,所以我只添加一些侧面 cmets:dbms_output.put_line(head_count); 行不会直接在 cx_Oracle 中执行任何操作,除非您执行一些额外的步骤,如 cx_Oracle 示例中所示 DbmsOutput.py .另一个评论是 11g 已经很老了。如果您使用的是“XE”版本,那么您应该考虑安装 XE 18c。
  • 为什么需要一个数据库来计算一个除法
  • 有需要移植到Oracle的SQL Server数据库语句列表。

标签: python oracle


【解决方案1】:

在 oracle 中,一种方法是使用 CTE,如下所示:

with cte as 
(select 200 as dispatchcount, 50 as headcount from dual)
select dispatchcount/headcount from cte

如果您希望两个变量都在不同的表中,则使用多个 cte,如下所示:

with cte1 as 
(select 200 as dispatchcount from dual),
cte2 as (select 50 as headcount from dual)
select dispatchcount/headcount from cte1 , cte2

【讨论】:

  • 即使 dispatchcount 和 headcount 位于不同的表中,如果有一个可以工作的解决方案,那就太好了。就我而言,我会考虑像这样重组查询,谢谢。
  • 好的,更新了答案。请检查更新部分
【解决方案2】:

是的,您可以使用准备好的 SQL 语句以及虚拟 dual 表,包括在元组中声明的参数的占位符,通过使用 cursor.fetchone() 考虑到您的情况只需要返回一行,例如

DispatchCount=200
HeadCount=50

sql  = """
          SELECT :1 / :2
            FROM dual
       """

cursor.execute(sql,(DispatchCount,HeadCount,))
rows = cursor.fetchone()
    
print(rows[0])

对于多行表,您也可以将fetchone() 替换为fetchall()

【讨论】:

  • 有效答案。我接受了大力水手的回答,因为我需要避免修改 python 代码。
猜你喜欢
  • 2013-10-22
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多