I have a question, I'm trying to make an insert in the local database, in a table with a column with type datetime.
cmd.Connection = conn.conectar();
cmd.CommandText = "insert into tab_item "
"values (@codVendedor, @codCleinte, @datavenda, @valorTotalVenda, @formapgmt)";
cmd.Parameters.AddWithValue("@codVendedor", codVendedor);
cmd.Parameters.AddWithValue("@codCleinte", codCliente);
cmd.Parameters.AddWithValue("@datavenda", Convert.ToDateTime(DateTime.Now));
cmd.Parameters.AddWithValue("@valorTotalVenda", valortotalvenda);
cmd.Parameters.AddWithValue("@formapgmt", formadepagamento);
cmd.ExecuteNonQuery();
mensagemretorno = "Sucesso para gerar venda";
This is the table structure in SQL:
create table tab_venda(
id int primary key not null identity(1, 1),
cod_vendedor int not null foreign key (id) references tab_pessoa,
cod_cliente int not null foreign key (id) references tab_pessoa,
dta_venda datetime not null,
valor_total_venda decimal (18, 2) not null,
forma_pagamento int not null
)
The error I get is the
System.Data.SqlClient.SqlException: Implicit casting from datetime data type to int is not allowed. Use the CONVERT function to run this query.
Can someone help me? I don't know how to proceed with this insert
I tried to use a dateTime.Now, because I need the exact date to finalize the sale, but it still didn't work, I tried to force a convert of that value (Convert.ToDateTime(DateTime.Now)) to datetime but without success.
CodePudding user response:
You need to specify the columns, or else it will try to insert starting with the first column, which is the autoidentity id
column in youe case:
cmd.CommandText = "insert into tab_item "
"(cod_vendedor, cod_cliente, dta_venda, valor_total_venda, forma_pagamento) "
"values (@codVendedor, @codCleinte, @datavenda, @valorTotalVenda, @formapgmt)";
Also, there's no need to use Convert.ToDateTime
on DateTime.Now
- it's already a DateTime
:
cmd.Parameters.AddWithValue("@datavenda", DateTime.Now);
but I see from your question that you added it thinking that was the problem, so you can safely remove it.
CodePudding user response:
Thank you all very much for the answers, the solution was defined as columns in the INSERT The problem has been resolved.
insert into tab_venda (cod_vendedor,cod_cliente,dta_venda,valor_total_venda,forma_pagamento) values (@codVendedor, @codCleinte, @datavenda, @valorTotalVenda, @formapgmt)