Volatil3
Volatil3

Reputation: 14988

asp mvc3: Search both string and Integer in a single query

I come across a very silly issue. I have a searchbox in which user can enter both numeric and string. Some of Where clauses are integer while others are string. My query is something like:

string keyword = "";
string query = "Select * from Table
where POrderNumber = {0}
AND
Fname LIKE '% {0}%'";
query = string.Format(query,keyword);

I am getting Data Conversion Error

Upvotes: 0

Views: 276

Answers (1)

IyaTaisho
IyaTaisho

Reputation: 863

My suggestion would be to make the query built conditionally.

int POrderNumber;
string keyword = "";
string query = "Select * from Table Where ";
if (Int32.TryParse(keyword, out POrderNumber))
  query += "POrderNumber = " + POrderNumber;
if (!string.IsNullOrEmpty(keyword))
  query += " AND Fname LIKE '%" + keyword + "%'";

You can simplify it a bit more if you want, but that is the basic gist of it.

Upvotes: 1

Related Questions