Update multiple rows with different values in a single SQL query

前端 未结 6 642
你的背包
你的背包 2020-12-13 09:15

I have a SQLite database with table myTable and columns id, posX, posY. The number of rows changes constantly (might inc

6条回答
  •  囚心锁ツ
    2020-12-13 09:57

    There's a couple of ways to accomplish this decently efficiently.

    First -
    If possible, you can do some sort of bulk insert to a temporary table. This depends somewhat on your RDBMS/host language, but at worst this can be accomplished with a simple dynamic SQL (using a VALUES() clause), and then a standard update-from-another-table. Most systems provide utilities for bulk load, though

    Second -
    And this is somewhat RDBMS dependent as well, you could construct a dynamic update statement. In this case, where the VALUES(...) clause inside the CTE has been created on-the-fly:

    WITH Tmp(id, px, py) AS (VALUES(id1, newsPosX1, newPosY1), 
                                   (id2, newsPosX2, newPosY2),
                                   ......................... ,
                                   (idN, newsPosXN, newPosYN))
    
    UPDATE TableToUpdate SET posX = (SELECT px
                                     FROM Tmp
                                     WHERE TableToUpdate.id = Tmp.id),
                             posY = (SELECT py
                                     FROM Tmp
                                     WHERE TableToUpdate.id = Tmp.id)
    
    
    WHERE id IN (SELECT id
                 FROM Tmp)
    

    (According to the documentation, this should be valid SQLite syntax, but I can't get it to work in a fiddle)

提交回复
热议问题