1

I have a complex select statement for an Access 2010 database which grabs data from multiple tables using several LEFT JOIN statements. The query works as expected and I get the entire table.

So now I want to add search functionality. One way was to add a WHERE clause at the end of the query and reference one of the JOINed tables' text field and compare it against some text (WHERE [All Names].Name LIKE "*Mark*").

Second option I tried was select * from (**complex sql here**) where **condition**

Now in both cases, when my condition is something simple like ([ID]<15), it works like a charm, but when I change it to ([Employee Name] LIKE "\*Mark\*") or the one in option 1, it produces an empty data table as if the request goes through, there is no error or exception, all the field names are present, but no rows are returned.

However, if I grab the full string of the generated SQL string (either option) using the debugger (or just dump it into a text file), and then with literally no changes put that string directly into a new Access query, it works fine and returns several fields where the name contains "Mark"

Very simply put, a query that works fine within Access, does not work from within C#.

So I am now confused

4

2 回答 2

3

您正在使用 OleDb 连接到 Access db 文件。在这种情况下,您必须使用 ANSI 通配符 ( %and _)Like而不是*and进行比较?

在您的WHERE子句中使用这样的模式。

WHERE [Employee Name] LIKE "%Mark%"

如果您希望查询在 Access 会话中的工作方式与在 OleDb 连接中的工作方式相同,请使用ALIKE而不是LIKE. ALIKE始终使用 ANSI 通配符。

WHERE [Employee Name] ALIKE "%Mark%"
于 2013-09-11T05:06:01.897 回答
1

Simon 的问题和 HansUp 的回答最终解决了我的问题。对于那些好奇或有类似问题的人,这里是完整的查询:

string query=
  "SELECT Employees.ID, " +
  "[All Names E].Name AS [Employee Name], " +
  "Titles.Title, " +
  "[All Names S].Name AS [Supervisor Name], " +
  "Employees.[Phone #], " +
  "Offices.[Office Location], " +
  "PCs.PC " +
  "FROM (((((Employees LEFT JOIN [All Names] as [All Names E] ON Employees.Employee = [All Names E].ID) " +
  "LEFT JOIN [All Names] as [All Names S] on Employees.Supervisor=[All Names S].ID) " +
  "LEFT JOIN Titles on Employees.Title=Titles.ID) " +
  "LEFT JOIN Offices on Employees.[Office Location]=Offices.ID) " +
  "LEFT JOIN PCs on Employees.PC=PCs.ID) " +
  "ORDER BY Employees.ID";

在此之前添加 where 子句ORDER BY确实WHERE ([All Names E].Name LIKE \"*Mark*\")可以在 Access 中工作。第二种方法是:

string searchQuery="select * from ("+query+") where ([Employee Name] like \"*Mark*\")";

这两种方法都在 Access 中完美运行,但我不知道有一个不同的通配符可用于 OleDB。

因此,将星号更改为百分号解决了这个问题。

再次感谢。

于 2013-09-11T16:25:14.320 回答