mariadbinsertconcatenation

MariaDB :Producing an insert from another table with concat


I want to produce an insert out of a table for another table with concat. All works well, besides a little devil ... At the end of the concat I get an ' after the ; Without the ' it works all well.

How may I get rid of the ' ?

Sample:

drop table if exists gf;create table gf(id int auto_increment primary key,datum date,time time,vornum int,name varchar(40),surname varchar(40),open varchar(40),krz varchar(5),knd varchar(5),titel varchar(40)unique,anfrage text,form varchar(12));
    drop table if exists knd;create table knd(id int auto_increment primary key,datum date,time time,vornum int,name varchar(40),surname varchar(40),open varchar(40),krz varchar(5),knd varchar(5),titel varchar(40)unique,anfrage text,form varchar(12));
    
    insert into knd values('0',current_date,current_time,'0','Myname','Myfirstname','MyOpen','MyKrz','MyKnd','MyWish','MyWish','MyForm');

     select CONCAT('insert into gf values(','''0'',''',datum,''',''',time,''',''',vornum,''',''',name,''',''',surname,''',''',open,''',''',krz,''',''',knd,''',''',titel,''',''',anfrage,''',''',form,''');''')from
    knd where id =1;

Result is:

insert into gf values('0','2025-05-17','23:02:03','0','Myname','Mylastname','MyOpen','MyKrz','MyKnd','MyWish','MyWish','MyForm');' (<little devil here)

Solution

  • A literal answer

    You inadvertently used a triple ''' at the end while you needed a single one:
    ,form,''');''')from
    should be:
    ,form,''');')from

    (see both queries in a fiddle)

    Going further

    … But using this kind of casting to string, on not always string columns (like times) and without escaping is dangerous:
    loss of precision, and more importantly risk of SQL injection or at least broken workflow if one of your fields contains a ', like in My wish it's to break this database.

    You can directly insert from a select, like running this query when your knd row has been validated:

    insert into gf
    select 0, datum,time,vornum,name,surname,open,krz,knd,titel,anfrage,form
    from knd where id =1
    

    (of course, contrary to the "textual insert", this requires that both gf and knd are in the same database; and that you keep rows in knd until they've been copied to gf)

    And if the validation is not waiting only for the user, but for other conditions too (verifying that the name is not empty, that the form still exists in some reference table), you can of course add those conditions to the where:

    …
    from knd where id =1 and length(name) >= 3 and …;
    

    Thus the validation occurs in the same database transaction as the insert avoiding inconsistencies that could occur due to data changing between your validation and your insert.