SQL参数化查询未返回正确的结果

时间:2014-04-25 18:02:40

标签: sql vb.net parameters

我的数据库中有一个视图,视图中有一行我正在尝试搜索。我在sql server中测试了它,它返回了正确的结果。但是,当我尝试使用vb中的参数时,它不会返回任何内容。我得到查询以返回正确结果的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 =“dunn”。

sql查询返回相应的行,但带参数的vb.net不返回任何内容。

1 个答案:

答案 0 :(得分:2)

将通配符(即%字符)移动到VB.net字符串中,然后再将其作为参数传递。

例如,在VB.net代码中执行此操作...

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

在LIKE语句中使用@search参数时,在SQL中,不要添加通配符,如下所示......

WHERE building LIKE @search

看到这篇SO帖子基本上是同一个问题...

How to use wildcards in SQL query with parameters