sql-server – Conversion failed while converting varchar value 'No' to data type tinyint

Question:

I'm trying to solve an error I think of converting a variable created by me to store data that is in an Excel sheet.

The error happens when I try to insert the data that is in this variable in SQL Server , that is, in (query).

code:

variable declaration:

string valmoradafiscaligualmoradalocal = "";

information search code:

case 47://coluna 21

if (((WS.Cells[linha, Contcoluna] as Excel.Range).Value) != null)
{
    valmoradafiscaligualmoradalocal = Convert.ToString((WS.Cells[linha, Contcoluna] as Excel.Range).Value);  
}
continue;

sql server insert code:

cmd.CommandText = "INSERT tabela_sacc (Morada_Fiscal_Igual_a_Morada_Local) VALUES ('" + valmoradafiscaligualmoradalocal.ToString() + "')";

connection.Open();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
connection.Close();
valgrupo = null;

Answer:

friend good afternoon

if the value you are trying to enter is an integer, try to strip the single quotes from your code

    cmd.CommandText = "INSERT tabela_sacc (Morada_Fiscal_Igual_a_Morada_Local) VALUES (" + valmoradafiscaligualmoradalocal + ")";

I recommend you use sqlparameter https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlparameter(v=vs.110).aspx where you define the type of table

Hope this helps

Scroll to Top