mardi 22 décembre 2015

Insert or Replace with selecting the currently generated id

I have following example table:

CREATE TABLE USER 
(
    USER_ID INTEGER PRIMARY KEY AUTOINCREMENT,
    USER_EMAIL VARCHAR(255) NOT NULL,
    USER_FIRSTNAME VARCHAR(255) NOT NULL, 
    USER_LASTNAME VARCHAR(255) NOT NULL,
    USER_STATUS VARCHAR(255) NOT NULL,
    UNIQUE
    (
        USER_EMAIL,
        USER_FIRSTNAME,
        USER_LASTNAME
    )
);

Now i do the following example operations:

INSERT INTO USER(USER_EMAIL, USER_FIRSTNAME, USER_LASTNAME, USER_STATUS) VALUES("Bob.Ross@painting.com", "Bob", "Ross", "registered");
INSERT INTO USER(USER_EMAIL, USER_FIRSTNAME, USER_LASTNAME, USER_STATUS) VALUES("Bob.Ross@painting.com", "Bob", "Ross", "activated");

This wont work because of the uniqe constraint but actually that is exactly what i want to do: I want the column USER_STATUS to update automatically when i perform an insert into an existing unique constraint.

I guess this is quite close to the solution: SQLite - UPSERT not INSERT or REPLACE but i faced a problem:

INSERT OR REPLACE INTO Employee (id, role, name) 
VALUES (  1, 
        'code monkey',
        (SELECT name FROM Employee WHERE id = 1)
      );

I dont insert my id manually. It is generated automatically.

How can i get the generated id for the current insert for my select statement?

EDIT

No, i dont want to use INSERT OR REPLACE or ON CONFLICT REPLACE because this is performing a delete + insert which is destroying the index. I will have huge amount of data and i dont want that.

Aucun commentaire:

Enregistrer un commentaire