0
I’m trying to pass parameter in mine select
and this bursting the exception:
It is necessary to declare the table variable
"@p_tabela"
.
using (SqlConnection conn = new SqlConnection(connectionString)
{
try
{
conn.Open();
var sql = "SELECT Id FROM @p_tabela";
SqlCommand command = new SqlCommand(sql, conn);
command.Parameters.Add(new SqlParameter("@p_tabela", tabela));
using (SqlDataReader reader = command.ExecuteReader()) // Estoura erro aqui
{
if (reader.Read())
{
return true;
}
}
return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
}
I’ve tried this too:
command.Parameters.AddWithValue("@p_tabela", tabela);
SqlCommand command = new SqlCommand(command, conn); command.Parameters.Add("@p_tabela", SqlDbType.VarChar); command.Parameters["@p_tabela"].Value = tabela;
Second try use from here: https://docs.microsoft.com/pt-br/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8 Error image:
We need to know more about the error. Anyway I’ve seen in your codes that you use exception the wrong way. Delete this
try-catch
because he’s of no use. Read more on https://answall.com/search?tab=votes&q=user%3a101%20exce%C3%A7%C3%a3o Should also use moreusing
and notfinally
.– Maniero
Good morning Leo.. All right.. Dude .. for PARAMETERS of the WHERE argument I use exactly with you demonstrated in the second mode..: command.Parameters.Addwithvalue("@p_table", table);. How little bag of C# my question is.. FROM @p_table WOULD ACCEPT the table name as PARAMETRO?? You know what I mean? To solve this QUICKLY in Usitan mode I would put it like this..: var sql = "SELECT Id FROM " + table; Since you have it as a variable I think it would do no harm.. But as I said a way to resolve NOW :) I don’t know if it would meet your need. Anything just talk :)
– Ricardo M.Souza
@Souza, I miss the delay, I did just this to test, I was having the same doubt.... And it really was that... I put Where to confirm and it worked...
– LeoHenrique