2014-04-25 180 views
1

我在我的數據庫中有一個視圖,並且該視圖有一列我正在嘗試搜索。我已經在sql server中測試過了,它返回了正確的結果。但是,當我用vb的參數嘗試它時,它不會返回任何東西。 SQL代碼,我得到一個查詢返回正確的結果看起來像SQL參數化查詢不返回正確的結果

SELECT * 
FROM 
    (SELECT 
     ROW_NUMBER() OVER (ORDER BY groupID DESC) AS Row, * 
    FROM 
     SchedulingGroup_VIEW 
    WHERE 
     (scheduled = 1) 
     AND ((building LIKE '%dunn%') OR (room LIKE '%dunn%') 
      OR (requestBy LIKE '%dunn%') OR (requestFor LIKE '%dunn%') 
      OR (groupID LIKE '%dunn%') OR (description LIKE '%dunn%')) 
     AND (NOT EXISTS (SELECT gID FROM facilitiesForm 
         WHERE facilitiesForm.gID <> gID))) AS TMP 
WHERE 
    (Row BETWEEN 0 AND 100) 

與參數的SQL看起來像

SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY groupID DESC) AS Row, * 
FROM schedulingGroup_VIEW 
WHERE (scheduled = 1) AND 
((building LIKE '%' + @search + '%') 
    OR (room LIKE '%' + @search + '%') 
    OR (requestBy LIKE '%' + @search + '%') 
    OR (requestFor LIKE '%' + @search + '%') 
    OR (groupID LIKE '%' + @search + '%') 
    OR (description LIKE '%' + @search + '%')) 
AND 
    (NOT EXISTS (SELECT gID FROM facilitiesForm 
    WHERE facilitiesForm.gID <> gID))) AS TMP WHERE (Row BETWEEN 0 AND 100) 

sqlComm.Parameters.AddWithValue("@search", info.search) 

與info.search =「唐恩」。

sql查詢返回相應的行,但帶參數的vb.net不返回任何內容。

回答

2

在將它作爲參數傳遞之前,將通配符(即%字符)移到VB.net字符串中。

例如,爲此在VB.net代碼...

sqlComm.Parameters.AddWithValue("@search", "%" + info.search + "%"); 

而在你的SQL當您使用LIKE語句中的@search參數,不加通配符,如下圖所示...

WHERE building LIKE @search 

看到這個SO後基本上是同樣的問題...

How to use wildcards in SQL query with parameters

+0

我對此投票並將其作爲答案。儘管我已經看到了這兩個參數。它也有助於使測試數據鏡像直播。謝謝。 – willJk

+0

雖然它可以防止SQL注入,但這更好。 – sovemp

+0

我也有同樣的問題嗎? – SearchForKnowledge