在 SQLite3 中是否有更好的方法来“foreach”此更新插入?

问题描述 投票:0回答:1

我正在尝试更新插入许多不同的值,其中调用之间的实际查询非常相似:

INSERT INTO `station` (`id`, `is_mirrored`) VALUES ('station1', TRUE) ON CONFLICT(`id`) DO UPDATE SET `is_mirrored`=TRUE;
INSERT INTO `station` (`id`, `is_mirrored`) VALUES ('station2', TRUE) ON CONFLICT(`id`) DO UPDATE SET `is_mirrored`=TRUE;
INSERT INTO `station` (`id`, `is_mirrored`) VALUES ('station3', TRUE) ON CONFLICT(`id`) DO UPDATE SET `is_mirrored`=TRUE;
INSERT INTO `station` (`id`, `is_mirrored`) VALUES ('station4', TRUE) ON CONFLICT(`id`) DO UPDATE SET `is_mirrored`=TRUE;

理想情况下,我希望创建一个以逗号分隔的

station.id
值列表,我可以运行此重复查询来简化它。如果它是一个简单的
insert
,我可以减少开销,但我不清楚如何在 SQLite3 中完成更新插入逻辑。

如有任何帮助,我们将不胜感激!

sql database sqlite optimization
1个回答
0
投票

这是一种在 SQL 中执行循环的方法

SELECT 
IDENTITY(int,1,1) as MYID,
value as StationID 
INTO #StationList
FROM STRING_SPLIT('Station1,Station2,Station3,Station4', ',');

DECLARE @MYID INT
DECLARE @StationID VARCHAR(50)

SET @MYID = (SELECT MIN(MYID) FROM #StationList)
WHILE EXISTS (SELECT 1 FROM #StationList WHERE MYID=@MYID)
BEGIN
    SET @StationID = (Select StationID FROM #StationList WHERE MYID=@MYID)
    
    INSERT INTO station (id, is_mirrored) VALUES (@StationID, 'TRUE') ON CONFLICT(id) DO UPDATE SET is_mirrored='TRUE';
    SET @MYID = @MYID + 1
END
© www.soinside.com 2019 - 2024. All rights reserved.