我想在 SQLite 中声明一个变量并在 insert
操作中使用它。
就像在 MS SQL 中一样:
declare @name as varchar(10)
set name = 'name'
select * from table where name = @name
例如,我需要获取 last_insert_row
并在 insert
中使用它。
我发现了一些关于绑定(bind)的东西,但我并没有真正完全理解它。
最佳答案
SQLite 不支持本地变量语法,但您可以使用内存中的临时表实现几乎相同的语法。
我在大型项目中使用了以下方法,效果非常好。
/* Create in-memory temp table for variables */
BEGIN;
PRAGMA temp_store = 2; /* 2 means use in-memory */
CREATE TEMP TABLE _Variables(Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT);
/* Declaring a variable */
INSERT INTO _Variables (Name) VALUES ('VariableName');
/* Assigning a variable (pick the right storage class) */
UPDATE _Variables SET IntegerValue = ... WHERE Name = 'VariableName';
/* Getting variable value (use within expression) */
... (SELECT coalesce(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'VariableName' LIMIT 1) ...
DROP TABLE _Variables;
END;
关于sql - 在 SQLite 中声明变量并使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7739444/