sql - 在 SQLite 中声明变量并使用它

标签 sql sqlite variables declaration

我想在 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/

相关文章:

mysql - 组查询不计算对应值

ruby-on-rails - 如何在 Rails 4.2 和 sqlite 中按星期几进行过滤?

java - 在 while 循环中显示数字

python - MATLAB 结构体数组的 Python 版本是什么

Bash:在变量中制作 cat merge braced files {}

SQL 服务器 : Nvarchar to Varchar

sql - 如何返回特定的字符串

sql - 如果没有找到记录则返回零

database - SQLite3 的线程安全性如何?

sql-server - 使用 Entity Framework 4 Code First 使用 SQL Server CE 4 或 SQLite 进行集成测试