Tharindu Senanayake Tharindu Senanayake - 1 year ago 42
SQL Question

Adding multiple values to a SQL Query in C#

public IHttpActionResult Post(ModelName data){
var query="Select * from Table where ColumnName ='"+data.ID+"'";

return Ok(Value);

In the above SQL query I want to add multiple ID's in data.ID. for an example I in one instance i need to get data for 2 ID's. in another time I need data from 20 ID's. Im using angular js to pass the json array with data. How can I do that. Do I have to write many data.Id1, data.id2 etc for all my Id data. Any help


As long as you are sanitising your inputs you can use:

var query = "Select * from Table where ColumnName in (" + list_of_ids + ")";

This will work whether you have one Id or several.

list_of_ids will have to be a comma delimited string of values:

"a, b, c, d"

so you'll need some conversion method for adding each id to the list.

You could build up an list of values:

var myList = new List<string>();

if (data.Id1 is set)


string list_of_ids = string.Join(",", myList);