Flávio Augusto Flávio Augusto - 5 months ago 8
SQL Question

Simple SQL query syntax error in controller asp.net mvc5

I tried to convert to int like other selects, but this case is a multiselect and the foreach doesn't work with type int. I tried this and it worked: (but)....

//var id_status = Convert.ToInt32(Request.Form["id_status"]);
var id_status = Request.Form["id_status"];
var id_cliente = Convert.ToInt32(Request.Form["id_cliente"]);

var sql = "SELECT * FROM ativacao INNER JOIN cliente ON ativacao.id_cliente = cliente.id WHERE ativacao.id_cliente =" + id_cliente;

if (id_status != null)
{
foreach (var itemselecionado in id_status)
{
sql = sql + " OR ativacao.status = '" + itemselecionado + "'";
}
}


However, this foreach is working even with the commas, that is SQL query isn't working.

How can I get correct SQL query?

Final value of the SQL variable:

"SELECT * FROM ativacao
INNER JOIN cliente
ON ativacao.id_cliente = cliente.id
WHERE ativacao.id_cliente =106
AND cliente.id_prospector = 2
AND cliente.id_executivo = 1
AND cliente.ano_cliente = '2015'
--> OR ativacao.status = '4'
OR ativacao.status = ','
OR ativacao.status = '5'
OR ativacao.status = ','
OR ativacao.status = '6' <--


I'm sorry if I cant explain very well, I don't know English very well.

Every help will be appreciated so much.

Answer

EDIT: You can just do this in your foreach loop:

if(itemselecionado == ',') continue;