What is wrong with my sqlite3 CASE statement?

后端 未结 1 1824
旧巷少年郎
旧巷少年郎 2021-01-23 19:56

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 IN         


        
相关标签:
1条回答
  • 2021-01-23 20:37

    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:

    Cursor c = 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')
    
    0 讨论(0)
提交回复
热议问题