我正在尝试在python中使用pyodbc运行SQL命令。 其中SQL命令包含多个SELECT命令和IF语句。
但是我收到如下错误
columns = [col_desc[0] for col_desc in cursor.description]
TypeError: 'NoneType' object is not iterable
import pyodbc
import pandas as pd
conn = pyodbc.connect("DRIVER={SQL Server};"
"SERVER=server_name;"
"DATABASE=master;"
"Trusted_Connection=yes;")
cursor = conn.cursor()
script="""
If object_id ('tempdb..#Temp1')is not null
drop table #Temp1
Select distinct a1.some_ID into #Temp1
from DOC.dbo.Document_tbl (NOLOCK)a1
from #Temp1 a1
If object_id ('tempdb..#Temp2')is not null
Drop table #Temp2
select distinct v2.some_data
into #Temp2 from tbl_name (nolock) v2
If object_id ('tempdb..#Results')is not null
drop table #Results
select distinct a1.*,b1.####
into #Results
from #Temp1 a1
left join #Temp2 b1 on a1.## = b1.##
Select * from #Results
"""
df = pd.read_sql(script, cnxn)
writer = pd.ExcelWriter('result.xlsx')
df.to_excel(writer, sheet_name ='bar')
writer.save()
答案 0 :(得分:0)
SQL命令文本称为匿名代码块。匿名代码块可以返回多个结果,每个结果可以是
以下示例失败...
sql = """\
SELECT 1 AS foo INTO #tmp;
SELECT * FROM #tmp;
"""
df = pd.read_sql_query(sql, cnxn)
# TypeError: 'NoneType' object is not iterable
...,因为第一个SELECT ... INTO
返回行数,第二个SELECT
返回结果集。
解决方法是使用SET NOCOUNT ON;
启动匿名代码块,该代码块将禁止行数并仅返回结果集:
sql = """\
SET NOCOUNT ON;
SELECT 1 AS foo INTO #tmp;
SELECT * FROM #tmp;
"""
df = pd.read_sql_query(sql, cnxn)
# no error