SQLite - UPSERT *not* INSERT or REPLACE

后端 未结 18 2592
猫巷女王i
猫巷女王i 2020-11-21 23:53

http://en.wikipedia.org/wiki/Upsert

Insert Update stored proc on SQL Server

Is there some clever way to do this in SQLite that I have not thought of?

18条回答
  •  盖世英雄少女心
    2020-11-22 00:16

    This method remixes a few of the other methods from answer in for this question and incorporates the use of CTE (Common Table Expressions). I will introduce the query then explain why I did what I did.

    I would like to change the last name for employee 300 to DAVIS if there is an employee 300. Otherwise, I will add a new employee.

    Table Name: employees Columns: id, first_name, last_name

    The query is:

    INSERT OR REPLACE INTO employees (employee_id, first_name, last_name)
    WITH registered_employees AS ( --CTE for checking if the row exists or not
        SELECT --this is needed to ensure that the null row comes second
            *
        FROM (
            SELECT --an existing row
                *
            FROM
                employees
            WHERE
                employee_id = '300'
    
            UNION
    
            SELECT --a dummy row if the original cannot be found
                NULL AS employee_id,
                NULL AS first_name,
                NULL AS last_name
        )
        ORDER BY
            employee_id IS NULL --we want nulls to be last
        LIMIT 1 --we only want one row from this statement
    )
    SELECT --this is where you provide defaults for what you would like to insert
        registered_employees.employee_id, --if this is null the SQLite default will be used
        COALESCE(registered_employees.first_name, 'SALLY'),
        'DAVIS'
    FROM
        registered_employees
    ;
    

    Basically, I used the CTE to reduce the number of times the select statement has to be used to determine default values. Since this is a CTE, we just select the columns we want from the table and the INSERT statement uses this.

    Now you can decide what defaults you want to use by replacing the nulls, in the COALESCE function with what the values should be.

提交回复
热议问题