Declare variable in SQLite and use it(在 SQLite 中声明变量并使用它)
问题描述
我想在 SQLite 中声明一个变量并在 insert 操作中使用它.
I want to declare a variable in SQLite and use it in insert operation.
就像在 MS SQL 中一样:
Like in MS SQL:
declare @name as varchar(10)
set name = 'name'
select * from table where name = @name
例如,我需要获取 last_insert_row 并在 insert 中使用它.
For example, I will need to get last_insert_row and use it in insert.
我发现了一些关于绑定的东西,但我并没有完全理解它.
I have found something about binding but I didn't really fully understood it.
推荐答案
SQLite 不支持本机变量语法,但您可以使用内存中的临时表实现几乎相同的效果.
SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.
我已经在大型项目中使用了以下方法并且效果很好.
I've used the below approach for large projects and works like a charm.
/* 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;
这篇关于在 SQLite 中声明变量并使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 SQLite 中声明变量并使用它
基础教程推荐
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
