【发布时间】:2018-04-30 23:30:55
【问题描述】:
我有一个 Python 脚本,它使用 pyodbc 库来运行一些查询,我让任务调度程序按设定的时间表运行。该脚本上周一直运行良好,没有问题,但突然遇到错误:
DatabaseError: Execution failed on sql 'select * from #output ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name '#output'. (208) (SQLExecDirectW)")
当我尝试使用pd.read_sql 从查询中提取该数据时,会出现此错误。非常奇怪的是,根本没有对脚本进行任何修改。直到今天它一直工作得很好。
我在 stackoverflow 上研究了类似的问题,并尝试使用相同的解决方案(创建全局临时表而不是本地临时表),但问题仍然存在。奇怪的是,查询包括两个临时表,#data 和 #output,我可以使用 pd.read_sql 毫无问题地访问 #data 的内容,但无论出于何种原因,尝试在其他临时表导致上述错误。
此处包含的代码本身可能有点长,但大部分情况下都是这样(如果不是问题,我很乐意分享整个内容):
connection = pyodbc.connect(...)
cursor = connection.cursor()
query = """create table #data (...)
... #some other commands here in the middle
create table #output (...)
... #two more lines of SQL commands and that's it
"""
cursor.execute(query)
totals = pd.read_sql("""select * from #output"""), connection)
cursor.execute(query) 行似乎不会产生错误,因为如果我只跑到那行,我会得到<pyodbc.Cursor at 0xef2eea0>。
感谢您的帮助。
编辑:我怀疑错误消息是由于 create table #output 语句之前有一个 while 循环部分,它以某种方式阻止了下一个命令正确执行。我使用上面的示例代码包含了更多细节:
connection = pyodbc.connect(...)
cursor = connection.cursor()
query = """create table #data (...)
... #some other commands here in the middle
declare @order int, @limit int, @check varchar(20)
set @order = 1
set @limit = (select count(*) from #data where [weekday] = 'Friday')
while @order <= @limit
begin
update #data
set [order] = @order
where #data.[date] = (select top 1 [date] from #data where [order] is null order by [date] asc)
if (select top 1 [weekday] from #data where [order] is not null order by [date] desc) = 'Friday'
set @order = @order + 1
update #data
set weekly_desc = (select top 1 weekly_desc from #data where [weekday] = 'Friday' and [order] is null order by [date] asc)
where [order] = @order
end
create table #output (...)
"""
cursor.execute(query)
totals = pd.read_sql("""select * from #output""", connection)
【问题讨论】:
-
从报错信息看来是表名#output没有正确传递,尝试打印名称并检查。
-
@Fact 所以我相信这个问题源于
create table #output之前发生的事情,这是一个while循环。不知何故,我认为 while 循环正在阻止执行下一行。我已经用 while 循环部分更新了上面的代码,看看是否有人能给我一些关于问题可能是什么的提示。 -
仔细检查您的代码。您更新后的示例括号不匹配,特别是
totals = pd.read_sql("""select * from #output"""), connection)有一个额外的)。 -
你发的错误信息也被屠了。你确定你没有只使用
pd.read_sql("""select * from ##output""" ...而不是pd.read_sql("""select * from #output""" ...? -
@Gord Thompson 那些错别字只是我在 OP 中编写的内容,而不是代码本身。不过,感谢您指出这一点!