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:
CREATE TEMP TABLE _Variables ( Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT ); INSERT INTO _Variables (Name) VALUES ('MyVariable');
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:
UPDATE _Variables SET IntegerValue = 10 WHERE Name = 'MyVariable';
Utilizing a Variable
Retrieve the variable's value within expressions:
SELECT ..., (SELECT COALESCE(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'MyVariable' LIMIT 1), ...
COALESCE
intelligently selects the appropriate value based on its data type.
Removing a Variable
Clean up after use:
DROP TABLE _Variables;
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!