I have a column containing many rows. I am passing into a method a list of values. I wish to return all rows where a substring of this column contains the value I am looking for.
At the moment, I am using CHARINDEXto check for a single substring, and appending on OR CHARINDEX for every subsequent substring. It’s quite messy, as I am sure you can appreciate.
So, at the moment, I have :
[Long SQL query]...
queryString.Append(string.Format(" (AND CHARINDEX( '{0}', Table.Column ) > 0 ", ListOfValues[0]));
foreach (string value in ListOfValues)
{
queryString.Append(string.Format("OR CHARINDEX( '{0}', Table.Column ) > 0 ", value));
}
queryString.Append(string.Format(")AND CHARINDEX( '{0}', Table.Column) > 0)"));
queryString.Append(")");
Is there are less syntactically horrific way to do this ? 🙂
Thanks
First off, putting string into a SQL query like that, is very risky! If you don’t watch out, you’re opening your application up for SQL injection http://en.wikipedia.org/wiki/SQL_injection.
And now to the answer:
To avoid SQL inject, try doing this instead:
As we’re doing string comparison here, I can’t think of a less messy way of handling it with a SQL server.