我正在这个连接中创建一个#Temp表,然后尝试将其转换为用户定义的表类型,并将其传递给存储过程。这在MicrosoftSQLServerManagementStudio中运行良好,但我无法使用pyodbc在python中运行。
SET NOCOUNT ON;
USE TestDB
DECLARE @Temp as dbo.TempType;
INSERT INTO @Temp SELECT * FROM #Temp;
SELECT * FROM @Temp;
(在实际的代码中,末尾的select语句将是存储过程,但在测试中,我正试图让它发挥作用)。尝试在光标上执行fetchall返回:
Traceback (most recent call last):
File "C:Anacondalibsite-packagesIPythoncoreinteractiveshell.py", line 2883, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-237-dfc0750240b3>", line 1, in <module>
dt = cur.fetchall()
ProgrammingError: No results. Previous SQL was not a query.
在同一个连接中,我可以选择*FROM#Temp,但转换为表类型似乎不允许我选择。有什么想法吗?
不确定这是否有帮助,但它解决了我在使用iPython笔记本电脑和带有#temp表的pyodbc时的问题:
import pyodbc
con = pyodbc.connect('Driver={SQL Server Native Client 10.0};Server=somedatabaseserver.com;Database=SomeDB;Trusted_Connection=yes;')
cur = con.cursor()
query1 = """SELECT * into #temp FROM [SomeDB].[SomeTable]"""
query2 = """SELECT * FROM #temp"""
cur.execute(query1)
cur.commit()
cur.execute(query2).fetchall()
这里的技巧是将提交到#temp查询中,然后对其执行操作。