Search code examples
javascriptsqlhtmlweb-sqlalter

Can I use question mark in ALTER query?


I tried to create a table and then add a bunch of new columns into it. It was implemented by Javascript (the database used is SQLite in websql I think):

var FFFNames = ["DEFAULTY", "LAGACY", "MATADATA"];

db.transaction(function (tx){
    tx.executeSql('CREATE TABLE IF NOT EXISTS ProjSetsT (ProjId unique)');
});

for (var i = 0; i < FFFNames.length; i++){
    db.transaction(function (tx){
        tx.executeSql('ALTER TABLE ProjSetsT ADD ? TINYINT(1)', FFFNames[i]);
    });
}

Well it did not work. The table got created but no columns added. Is question mark allowed in ALTER or there is something else wrong?

[Updated on 20th Sep]: I tried different syntax, like "ALTER TABLE tablename ADD COLUMN ? datatype", but it still does not work.

I also tried code like this:

db.transaction(function (tx){
    tx.executeSql('ALTER TABLE ProjSetsT ADD COLUMN ? TINYINT(1)', "TEST");
});

There is no warning but just does not work.

I also tried:

var AAA = "TEST";
db.transaction(function (tx){
    tx.executeSql('ALTER TABLE ProjSetsT ADD COLUMN ? TINYINT(1)', AAA);
});

This time I got error:

Uncaught Error: TYPE_MISMATCH_ERR: DOM Exception 17


Solution

  • It's ALTER TABLE ... ADD COLUMN. Also, the second parameter must be an array.

    for (var i = 0; i < FFFNames.length; i++){
        db.transaction(function (tx){
            tx.executeSql('ALTER TABLE ProjSetsT ADD COLUMN ? TINYINT(1)', [FFFNames[i]]);
        });
    }
    

    (Update): Apparently, the above query will not work because each of the column names will be treated as 'text', thereby producing an error. This is what you can do for that query to work:

    for (var i = 0; i < FFFNames.length; i++){
        db.transaction(function (tx){
            tx.executeSql('ALTER TABLE ProjSetsT ADD COLUMN '+FFFNames[i]+' TINYINT(1)');
        });
    }