SQLite lacks native variable support, but we can effectively mimic variable behavior using temporary in-memory tables—a robust method even for extensive projects.
Creating a Variable
First, create a temporary table to hold variable names and their values:
<code class="language-sql">CREATE TEMP TABLE _Variables ( Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT ); INSERT INTO _Variables (Name) VALUES ('MyVariable');</code>
This establishes _Variables
, a temporary table storing variable names and their values across various data types.
Assigning a Value
Assign values based on their data type:
<code class="language-sql">UPDATE _Variables SET IntegerValue = 10 WHERE Name = 'MyVariable';</code>
Utilizing a Variable
Retrieve the variable's value within expressions:
<code class="language-sql">SELECT ..., (SELECT COALESCE(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'MyVariable' LIMIT 1), ...</code>
COALESCE
intelligently selects the appropriate value based on its data type.
Removing a Variable
Clean up after use:
<code class="language-sql">DROP TABLE _Variables;</code>
Alternatively, temporary tables are automatically dropped when a transaction concludes with END;
.
The above is the detailed content of How Do I Declare, Use, and Deallocate Variables in SQLite?. For more information, please follow other related articles on the PHP Chinese website!