Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variable in SQLite and use it

I want to declare a variable in SQLite and use it in insert operation.

Like in MS SQL:

declare @name as varchar(10) set name = 'name' select * from table where name = @name 

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.

like image 408
Muhammad Nour Avatar asked Oct 12 '11 11:10

Muhammad Nour


People also ask

Does SQLite support variables?

SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.

How do you set a declared variable in SQL?

Firstly, if we want to use a variable in SQL Server, we have to declare it. The DECLARE statement is used to declare a variable in SQL Server. In the second step, we have to specify the name of the variable. Local variable names have to start with an at (@) sign because this rule is a syntax necessity.

Can we use DECLARE in SQL?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.


2 Answers

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; 
like image 134
Herman Schoenfeld Avatar answered Oct 09 '22 03:10

Herman Schoenfeld


For a read-only variable (that is, a constant value set once and used anywhere in the query), use a Common Table Expression (CTE).

WITH const AS (SELECT 'name' AS name, 10 AS more) SELECT table.cost, (table.cost + const.more) AS newCost FROM table, const  WHERE table.name = const.name 

SQLite WITH clause

like image 24
DenverCR Avatar answered Oct 09 '22 03:10

DenverCR