[英]"ProgrammingError: No results. Previous SQL was not a query." while trying to truncate a table
[英]pyodbc & MS SQL Server - “No results. Previous SQL was not a query.”
我正在使用 pyodbc 從 Microsoft SQL Server 檢索數據。 查詢的形式如下
SET NOCOUNT ON --Ignore count statements
CREATE TABLE mytable ( ... )
EXEC some_stored_procedure
INSERT mytable
--Perform some processing...
SELECT *
FROM mytable
存儲過程對包含NULLs
值執行一些聚合,以便Warning: Null value is eliminated by an aggregate or other SET operation.
形式為Warning: Null value is eliminated by an aggregate or other SET operation.
發出。 這會導致 pyodbc 無法檢索數據並顯示錯誤消息No results. Previous SQL was not a query.
No results. Previous SQL was not a query.
我試圖通過設置SET ANSI_WARNINGS OFF
來禁用警告。 但是,查詢隨后失敗並顯示錯誤消息Heterogeneous queries require the ANSI_NULLS and ANSI_WARNINGS options to be set for the connection. This ensures consistent query semantics. Enable these options and then reissue your query.
Heterogeneous queries require the ANSI_NULLS and ANSI_WARNINGS options to be set for the connection. This ensures consistent query semantics. Enable these options and then reissue your query.
.
是否有可能
請注意,我無權更改存儲過程。
將查詢結果存儲在臨時表中,並將語句作為兩個查詢執行:
with pyodbc.connect(connection_string) as connection:
connection.execute(query1) #Do the work
result = connection.execute(query2) #Select the data
data = result.fetchall() #Retrieve the data
第一個查詢完成了繁重的工作,其形式為
--Do some work and execute complicated queries that issue warning messages
--Store the results in a temporary table
SELECT some, column, names
INTO #datastore
FROM some_table
第二個查詢檢索數據並具有以下形式
SELECT * FROM #datastore
因此,在執行第一個查詢時發出所有警告消息。 它們不會在執行第二個查詢期間干擾數據檢索。
我通過在有問題的視圖或存儲過程周圍打開和關閉 ansi_warnings 來減輕這個錯誤。
/* vw_someView aggregates away some nulls and presents warnings that blow up pyodbc */
set ANSI_WARNINGS off
select *
into #my_temp
from vw_someView
set ANSI_WARNINGS on
/* rest of query follows */
這假設產生聚合警告的實體也不需要打開警告。 如果它抱怨,這可能意味着實體本身有一部分這樣的代碼需要切換 ansi_warnings(或重寫以消除聚合。)
一個問題是我發現如果我嘗試將它作為跨服務器查詢運行,這個切換仍然會返回“異構”警告。 此外,在調試時,很容易進入 ansi_warnings 被觸發的狀態,當您沒有意識到它並且您似乎無緣無故地開始收到異構錯誤時。 只需單獨運行“set ANSI_WARNINGS on”行即可讓自己恢復到良好狀態。
最好的辦法是添加 try: except: block
sql="sp_help stored_procedure;"
print(">>>>>executing {}".format(sql))
next_cursor=cursor.execute(sql)
while next_cursor:
try:
row = cursor.fetchone()
while row:
print(row)
row = cursor.fetchone()
except Exception as my_ex:
print("stored procedure returning non-row {}".format(my_ex))
next_cursor=cursor.nextset()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.