如何在SqLite中的一个查询中更新和选择一行?

时间:2009-12-17 13:43:39

标签: sql mysql sqlite

我想在SqLite中的一个查询中更新并选择一行。在MySql中,我想要的查询看起来像这样:

SET @update_id := -1;
UPDATE data SET `Status` = 'running', Id = (SELECT @update_id := Id) 
  WHERE `Status` = 'scheduled' LIMIT 1;
SELECT * FROM data WHERE id=@update_id;"

以上查询会将状态设置为'正在运行',并将变量 @update_id 的值设置为已修改行的 Id 对于第一行具有“已安排”的状态,并使用变量 @update_id 来获取完整的已修改行。

重点是我需要选择UPDATE语句修改过的行

但据我所知,SqLite不支持变量。

如何为SqLite重写上面的MySQL查询?

2 个答案:

答案 0 :(得分:4)

您需要declare and use variables in whatever program you write that runs SQLite statements

谢天谢地,您可以使用bind variables in SQLite

//1.  Fetch the id into whatever language you are using:
SELECT id FROM DATA WHERE status = 'scheduled' LIMIT 1;

//2. Retrieve the id value from Step 1's resultset
int id = [id value from the resultset];

//3. Construct the update statement
parsed_sql_stmt stmt = parse_sql(UPDATE DATA SET STATUS = 'running' WHERE ID = ?);

//4. Execute update statement
exec_stmt(stmt, id);

//5. Select everything in the DATA table for that record
stmt = parse_sql(SELECT * FROM DATA WHERE id = ?);
exec_stmt(stmt, id);

sheepsimulator是对的 - 这是三个单独的陈述。

答案 1 :(得分:1)

答案取决于您执行代码的位置。

如果你想在SQLite的命令行界面中使用变量,不,没有会话变量。你那里运气不好。

如果要在通过官方C ++ API(或其他一些API)连接到SQLite数据库时使用变量,则需要使用bind variables表示法(请参阅该页面上的3.0)。