2013-04-16 128 views
2

我正在使用pyodbc從Microsoft SQL Server中檢索數據。該查詢是採用以下形式pyodbc&MS SQL Server - 「沒有結果,以前的SQL不是查詢。」

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.的發出警告值有一些聚集。這導致pyodbc無法檢索數據並顯示錯誤消息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.

是否有可能

  • 禁用警告
  • 或有pyodbc忽略警告?

請注意,我沒有權限更改存儲的過程。

+0

你的語句之間不需要分號嗎? ';'?我真的在問。我不知道。 –

+0

@JoeFrambach:不,不需要分號。 –

回答

2

存儲查詢的臨時表的結果,並執行該語句爲兩個查詢:

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 

因此,所有警告消息都是在執行第一個查詢時發佈。它們在執行第二個查詢期間不會干擾數據檢索。

+0

從Till的上述答案不起作用,因爲第二個查詢不知道即使該連接沒有被刪除,該表是什麼。但是,如果您使用全局臨時表,它將起作用。例如:## datastore – 2015-04-06 16:20:38

+0

這似乎很奇怪,因爲臨時表的範圍是每個會話(https://msdn.microsoft.com/en-us/library/ms174979.aspx)而不是每個查詢。你是否放棄了會話,但保持連接還活着?我會告誡不要使用全局臨時表,因爲多個用戶同時執行相同的查詢可能會導致衝突。 –