Skip to content Skip to sidebar Skip to footer

What Is Wrong With My Sqlite3 Case Statement?

My code follows: SELECT COUNT(_id) AS count FROM general WHERE _id = 1 CASE WHEN count > 0 THEN UPDATE general SET userGivenId = 'xxx' WHERE _id = 1 ELSE INSERT INTO general (us

Solution 1:

SQLite does not have any control logic because this would not make sense in an embedded database (there is no separate server machine/process whose asynchronous execution could improve performance). CASE can be used only for expressions, not for entire commands.

Handle the control logic in your app:

Cursorc= db.rawQuery("SELECT 1 FROM general WHERE _id = 1", null);
if (c.moveToFirst())
    db.execSQL("UPDATE general SET userGivenId = 'xxx' WHERE _id = 1");
else
    db.execSQL("INSERT INTO general (userGivenId) VALUES ('xxx')");

For these particular commands, if you have a unique constraint on the _id column (and a primary key is constrained to be unique), you can use the INSERT OR REPLACE command:

INSERT OR REPLACE INTO general(_id, userGivenId) VALUES(1, 'xxx')

Post a Comment for "What Is Wrong With My Sqlite3 Case Statement?"