2015-11-18 68 views
0

我已經使用pydoc從sql數據庫中獲取數據。Python/pyodbc - WHERE語句過濾日期?

我想使用WHERE語句來過濾日期。我有:

cursor.execute("SELECT isnull(SOP30200.SOPNUMBE,''), isnull(SOP30200.docdate,'') from SOP30200 where SOP30200.docdate > datetime.datetime(2015,1,1,0,0)") 

,我得到的錯誤:

ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot find either column "datetime" or the user-defined function or aggregate "datetime.datetime", or the name is ambiguous. (4121) (SQLExecDirectW)') 

沒有WHERE語句我順利拿到數據。我確實檢查了被拖出的「docdate」字段的類型,它是datetime.datetime。

編輯:還應該指出的是,所提取的日期是在形式datetime.datetime(2013, 5, 8, 0, 0)

+1

你必須使用'特定的SQL server''date'在'where'條款'SOP30200.docdate>「1/1/2015'' –

+0

能否請你詳細說明,我不知道什麼是SQL Server特定的日期。謝謝 –

+0

你真的指'pydoc'嗎?我從標籤猜測你是指'pyodbc'? – mgilson

回答

4

你需要注入/使用參數插值的日期。 SQL服務器正在嘗試按原樣運行SQL語句,並且期望數據庫上存在datetime.datetime(..)函數。

cursor.execute("SELECT isnull(SOP30200.SOPNUMBE,''), isnull(SOP30200.docdate,'') from SOP30200 where SOP30200.docdate > ?", datetime.datetime(2015,1,1,0,0)) 

http://mkleehammer.github.io/pyodbc/ - 參數部分

2

「datetime.datetime」 不是SQL功能,是類Python標準庫。

可能是:

cursor.execute("SELECT isnull(SOP30200.SOPNUMBE,''), isnull(SOP30200.docdate,'') from SOP30200 where SOP30200.docdate > ?", datetime.datetime(2015,1,1,0,0))