2015-02-11 70 views
-1

嗨空SQL錯誤我試圖使用一個SQL字符串的訪問數據庫提取查詢和我有困難獲取代碼才能正常工作。如果我使用下面的代碼忽略參數如果在VB.NET

" select [incident id] as incidentid, ([incident ID] &' '&[incident date]) as incisearch from incident where (@supplier is null or [stock supplier] = @supplier)" 

如果輸入了一個@supplier參數,它只會返回一個結果,如果我用下面的代碼

" select [incident id] as incidentid, ([incident ID] &' '&[incident date]) as incisearch from incident where ([stock supplier] is null or @supplier)" 

它只能返回空的結果,無論輸入參數@supplier。我今天早上已經試過了這個代碼的幾種組合/變體,如果@supplier爲空,並且在輸入@supplier參數時顯示相關結果,我不能得到它的結果。有人可以告訴我我的代碼錯在哪裏嗎?

+0

其中([現貨供應商]爲空或[現貨供應商] = @supplier) – Crowcoder 2015-02-11 11:58:40

+0

第一個應該工作。你確定@supplier爲空嗎?你是否將DBNull作爲參數發送? – 2015-02-11 14:02:24

+0

我不發送DBnull作爲參數,我不知道這是如何工作的。我正在使用的參數設置是Dim supplier As New OleDbParameter(「@ supplier」,OleDbType.VarChar,100) supplier.Value = txt_supplier.Text command.Parameters.Add(supplier) – Boneyt 2015-02-11 16:07:46

回答

4
where ([stock supplier] is null or @supplier) 

它始終是值得測試您的SQL,與樣本數據,直接第一。

你會發現這是一個語法錯誤,沒有像column = a or b表達式語法。相反,你需要這樣的東西:

where (([stock supplier] is null) or ([stock supplier] = @supplier)) 

,或者更可能:

where ((@supplier is null) or ([stock supplier] = @supplier)) 

這將永遠是正確的(返回所有行)如果參數本身無效。

+0

感謝您的回覆我已經嘗試過當我在@supplier中輸入值時,它仍然只顯示結果 – Boneyt 2015-02-11 16:06:17

+0

直接對數據庫嘗試SQL(手動替換參數中的Access,因爲Access不支持SQL變量)。任何錯誤都應該爲您提供有關問題的線索。 – Richard 2015-02-11 16:33:56

+0

嗨對不起,遲到的迴應,所以我已經嘗試了SQL直接在訪問工作時給供應商參數,使部分工作正常,我不知道如何測試是零部分,因爲我假設爲這我只是省略SQL命令的哪一部分。 – Boneyt 2015-02-15 10:57:06

1

嘗試使用下面的代碼段

select 
    [incident id] as incidentid, 
    ([incident ID] &' '&[incident date]) as incisearch 
from incident 
where ([stock supplier]=isnull(@supplier,[stock supplier])) 
+1

取決於[股票供應商]是否可以爲空。 – 2015-02-11 14:20:37