Roberto Sánchez
Roberto Sánchez

Reputation: 11

How Insert on table IF some value is in database

There is a syntax problem on Asp.Net when I try to run an insert on a table if I have a vlaue in another table that I look for.

I tried different queries and datareaders but that generates a problem, one of the 2 datareaders needs to be closed.

        con.Open();

        String insertRegInfo = "INSERT INTO Login (NumEmp,Nombre,Apellido,Codigo) values (@NumEmp, @Nombre,@Apellido,@Codigo) SELECT NumEmp from Empleados WHERE NumEmp = " + TxtNumEmp.Text +"" ;

        MySqlCommand command = new MySqlCommand(insertRegInfo, con);

            LblConfirm.Text = "Confirmado";

            command.Parameters.AddWithValue("@NumEmp", TxtNumEmp.Text);
            command.Parameters.AddWithValue("@Nombre", TxtNombre.Text);
            command.Parameters.AddWithValue("@Apellido", TxtApellido.Text);
            command.Parameters.AddWithValue("@Codigo", TxtCodigo.Text);

            command.ExecuteNonQuery();

        con.Close();

I expect to insert data into the table if any value is true.

Upvotes: 0

Views: 48

Answers (1)

Dalorzo
Dalorzo

Reputation: 20014

Let me start saying that this is a terrible coding practice:

 String insertRegInfo = "INSERT INTO Login (NumEmp,Nombre,Apellido,Codigo) values (@NumEmp, @Nombre,@Apellido,@Codigo) SELECT NumEmp from Empleados WHERE NumEmp = " + TxtNumEmp.Text +"" ;

Better is:

String insertRegInfo = "INSERT INTO Login (NumEmp,Nombre,Apellido,Codigo) 
SELECT NumEmp,@Nombre,@Apellido,@Codigo from Empleados WHERE NumEmp = @NumEmp" ;

You should use parameters instead and better even Store Procedures.

However, to answer your question. All you need to do is match the number of columns of your SQL Command.

INSERT INTO Login (NumEmp,Nombre,Apellido,Codigo) 
SELECT NumEmp, @Nombre,@Apellido,@Codigo from Empleados WHERE…

Note that I removed the values section from the insert. That is not required

Upvotes: 3

Related Questions