If Concat insert result - mysql

I have a problem, I am making an insert using the concat to generate multiple inserts, however I realize that a null field is affecting all the queries, since the records that have null in their field, their insert is not generated correctly , now when integrating an IF() validation in the value of the field where the problem is caused, mysql sends me an error therefore the query is not executed
This is my query insert
SELECT concat ( "INSERT INTO `erp_gamma`.`partner` (`n_partner_id`, `n_activo`, `c_apellido_materno`, `c_apellido_paterno`, `c_correo_electronico`, `n_dias_credito`, `c_identificador`, `c_json`, `d_limite_credito`, `c_nombre`, `n_persona_fisica`, `c_razon_social`, `c_rfc`, `n_status`, `n_corporativo_sucursal_id`, `n_partner_tipo_id`, `c_codigo_postal`, `n_numero_telefonico`, `create_date`, `update_date`, `c_cp_fiscal`, `c_regimen_fiscal`, `c_sistema_id_serie_numerico`, `n_sistema_id_numerico`, `c_id_migracion`) VALUES (NULL, '1', '",partner.contacto_nombre,"', '",partner.contacto_nombre,"', '",partner.contacto_email,"', '",partner.control_dias_credito,"', '11111', '{\"id_calle_cliente_md\":\"",partner.contacto_calle,"\",\"id_colonia_cliente_md\":\"",partner.contacto_colonia,"\",\"id_ciudad_cliente_md\":\"",partner.contacto_ciudad,"\",\"id_estado_cliente_md\":\"",partner.contacto_estado,"\",\"id_cp_cliente_md\":\"",partner.contacto_cp,"\",\"id_telefono2_cliente_md\":\"",partner.contacto_telefono2,"\",\"id_celular_cliente_md\":\"",partner.contacto_telefono3,"\",\"id_fax_cliente_md\":\"",partner.contacto_fax,"\",\"id_web_cliente_md\":\"",partner.contacto_web,"\",\"id_tipoprecio_cliente_md\":\"",partner.control_tipo_precio_default,"\",\"id_calle_rfc_cliente_md\":\"",partner.factura_calle,"\",\"id_colonia_rfc_cliente_md\":\"",partner.factura_colonia,"\",\"id_ciudad_rfc_cliente_md\":\"",partner.factura_ciudad,"\",\"id_estado_rfc_cliente_md\":\"",partner.factura_estado,"\"}', '",partner.control_limite_credito,"', '",partner.contacto_nombre,"', '1', '",partner.factura_nombre,"', '",partner.factura_rfc,"', '1', '122', '1', '",partner.contacto_cp,"', '",partner.contacto_telefono1,"', now(), now(), '",partner.factura_cp,"', "IF(partner.factura_regimen_fiscal IS NULL," ", partner.factura_regimen_fiscal)", 'TP1_20', '20', '",partner.sku,"' );")
FROM partner
WHERE partner.tipo_partner = 1 AND partner.status =1;
I hope the inserts can be generated with the records I need

I post the query as it is as i never can test it
i added a lot of spaces, but i think it is more a problem from mysql workbench, as that big concat, aren't usually done, so the parser will get into trouble
The misstale you made is that you have is
IF(partner.factura_regimen_fiscal IS NULL," ", partner.factura_regimen_fiscal)
must be in commas, as it is ntpart if the string that you are combining
SELECT concat ( "INSERT INTO `erp_gamma`.`partner` (`n_partner_id`, `n_activo`, `c_apellido_materno`, `c_apellido_paterno`, `c_correo_electronico`, `n_dias_credito`, `c_identificador`, `c_json`, `d_limite_credito`, `c_nombre`, `n_persona_fisica`, `c_razon_social`, `c_rfc`, `n_status`, `n_corporativo_sucursal_id`, `n_partner_tipo_id`, `c_codigo_postal`, `n_numero_telefonico`, `create_date`, `update_date`, `c_cp_fiscal`, `c_regimen_fiscal`, `c_sistema_id_serie_numerico`, `n_sistema_id_numerico`, `c_id_migracion`) VALUES (NULL, '1', '"
,partner.contacto_nombre,"', '",partner.contacto_nombre,"', '",partner.contacto_email,"', '"
,partner.control_dias_credito,"', '11111', '{\"id_calle_cliente_md\":\" "
,partner.contacto_calle,"\",\"id_colonia_cliente_md\":\" "
,partner.contacto_colonia," \",\"id_ciudad_cliente_md\":\" ",partner.contacto_ciudad," \",\"id_estado_cliente_md\":\" "
,partner.contacto_estado,"\",\"id_cp_cliente_md\":\" ",partner.contacto_cp," \",\"id_telefono2_cliente_md\":\" "
,partner.contacto_telefono2," \",\"id_celular_cliente_md\":\" ",partner.contacto_telefono3," \",\"id_fax_cliente_md\":\" "
,partner.contacto_fax," \",\"id_web_cliente_md\":\" ",partner.contacto_web," \",\"id_tipoprecio_cliente_md\":\" "
,partner.control_tipo_precio_default," \",\"id_calle_rfc_cliente_md\":\" ",partner.factura_calle," \",\"id_colonia_rfc_cliente_md\":\" "
,partner.factura_colonia," \",\"id_ciudad_rfc_cliente_md\":\" ",partner.factura_ciudad," \",\"id_estado_rfc_cliente_md\":\" "
,partner.factura_estado," \"}', ' ",partner.control_limite_credito,"', '",partner.contacto_nombre
,"', '1', '",partner.factura_nombre,"', '",partner.factura_rfc,"', '1', '122', '1', '"
,partner.contacto_cp,"', '",partner.contacto_telefono1,"', now(), now(), '"
,partner.factura_cp,"', ",IF(partner.factura_regimen_fiscal IS NULL," ", partner.factura_regimen_fiscal),", 'TP1_20', '20', '",partner.sku,"' );")
FROM partner
WHERE partner.tipo_partner = 1 AND partner.status =1;

Try using a case statement formatted something like this;
case when partner.factura_regimen_fiscal IS NULL then "" else
partner.factura_regimen_fiscal end

Related

Error running SQL statement generated in code

String query = "INSERT INTO `new_db2`(`name`, `price`, `add_date`, `image`) " + "VALUES ('"+name+"','"+p_price+"','"+date+"','"image"')";
i have ';' error expected in this Sql query please help me to solve this
I don't know the language you are using (I suppose Java) but may be you should write the statement like this:
String query = "INSERT INTO `new_db2`(`name`, `price`, `add_date`, `image`) " + "VALUES ('"+name+"','"+p_price+"','"+date+"','"+image+"')";
(lack of + before and after image)

SQL INSERT with parameter as query

How can I insert parameter with value from database.
I have some field and I should insert value from this database + 1 (with plus one)
For example
myCommand.CommandText =
"INSERT INTO GAMES (GAME_NR, GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES (#game_nr, #game_player_id, #game_nrontable, #game_role_id)"
'Example
myCommand.Parameters.Add("#game_nr", SqlDbType.Int).Value = **"(SELECT MAX(GAME_NR) FROM GAMES)" + 1**
You don't. You make GAME_NR and auto-incremented primary key:
create table games (
game_nr int auto_increment primary key,
. . .
);
Then you do the insert as:
INSERT INTO GAMES (GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID)
VALUES (#game_player_id, #game_nrontable, #game_role_id);
Let the database do the work.
You don't need the parameter, you can try following code.
myCommand.CommandText =
"INSERT INTO GAMES (GAME_NR, GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES ((SELECT MAX(GAME_NR) + 1 FROM GAMES), #game_player_id, #game_nrontable, #game_role_id)"
But it looks like a primary key of the table. If Game_Nr is pr, You should use auto-inc. identity, then you don't need this param.
It will be.
myCommand.CommandText =
"INSERT INTO GAMES (GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES (#game_player_id, #game_nrontable, #game_role_id)"

how to handle very long SQL INSERT statement in mysql

I am using the following (python) code to generate a (MySQL) SQL INSERT statement (there are more columns, I left them out for simplicity):
mylist = [('1', '2', '3'),
('4', '5', '6'),
.
.
.
('7', '8', '9')]
sql_statement = "insert into mytable (col1, col2, col3) values "
for i in mylist:
if sql_statement == "insert into mytable (col1, col2, col3) values ":
# append this for the 1st element
sql_statement += "(" + i[0] + ", " + i[1] + ", " + i[2] + ")"
else:
# append this for everything else
sql_statement += ", (" + i[0] + ", " + i[1] + ", " + i[2] + ")"
which results in a string like the following:
sql_statement = "insert into mytable (col1, col2, col3) values (1, 2, 3), (4, 5, 6), ... (7, 8, 9)"
I then use sql_statement to execute the sql statement.
the issue with this approach is that the sql_statement string is getting to long and the insert does not consider all data.
any suggestions how to handle this?
UPDATE: prepared statement is the way to go. with that the (python) code looks like this:
sql_statement = "insert into mytable (col1, col2, col3) values (%s, %s, %s)"
for i in mylist:
cursor.execute(sql_statement, i)
Does the python library you are using supported prepared parameterized queries? I've found the performance difference between multi-value inserts such as this and repeated executions of prepared statements (in .Net at least) to be minimal in all but extreme cases. (In those cases, a mix of the two is optimal.)
Alternatively, just keep track of your query length, execute before it gets too big, and reinitialize the string & continue until all rows are handled.
Create a transaction and do insert one by one. and finally commit it. So only in one call all insert operation commit.

Error in Mysql query Insert or update

I am a little bit desesperate with this query, I can't find my fault:
INSERT INTO device (
Device_UUID,
Model,
Manufacturer,
Latitude,
Longitude,
Type,
Registration_Date,
Status,
API_Source)
values (
'WW',
'a',
'v',
'0.00',
'0.00',
'BUS',
'2014-01-01 12:11:11',
'1',
'R')
ON DUPLICATE KEY UPDATE
Model = "wwww",
Manufacturer = "bbbbb",
Registration_Date = "2014-01-01 12:11:11";
All fields are String, even latitud and longitude
Type is a keyword. Try to put Type inside some ".

Function NOW() on Qt

I'm trying to implement this query with Qt:
mysqlpp::Query query = acdb.query();
query << "INSERT INTO jobs (jobType, creationDate, reelType)
VALUES('ARCHIVE', NOW(), '" + reelType + "')";
where NOW() returns the current date and time.
This my code on Qt:
QSqlQuery query;
query.prepare("INSERT INTO jobs (jobType, creationDate, reelType) VALUES ('ARCHIVE',
'NOW()', '" + reelType + "')");
here NOW returns 0000-00-00 00:00:00
Is there a similar function?
You are trying to insert the string value 'NOW()' into the datetime field, hence resulting in an invalid value:
"INSERT INTO jobs (jobType, creationDate, reelType) VALUES ('ARCHIVE',
'NOW()', '" + reelType + "')");
Replace it with:
"INSERT INTO jobs (jobType, creationDate, reelType) VALUES ('ARCHIVE',
NOW(), '" + reelType + "')");
Btw. NOW() is a pure SQL function. It doesn't matter which platform or framework you use to send the query, it is entirely evaluated by the SQL server.