How can I use a variable in a SQL query without using dynamic SQL and the concat method?
I’d love to be able to declare variables at the start of a script to then use them throughout the script (e.g. table names)
Here’s an example of what I’d like to do:
declare variables
Set @Table1 = 'WhatsOn_20141208'
-- drop and re-create table
drop table if exists @Table1;
CREATE TABLE @Table1 (
rac_account_no varchar(100),
addressLine2 varchar(100)
);
-- load data into table
LOAD DATA LOCAL INFILE 'C:/Example.txt'
INTO TABLE @Table1
FIELDS TERMINATED BY '|'
ENCLOSED BY '"' LINES TERMINATED BY '\n'
IGNORE 1 LINES;
-- update addressLine2 column
Update @Table1
set addressLine2 = REPLACE(addressLine2,"*UNKNOWN*","");
If the table name changes, I want to be able to change it in the variables once rather than doing a find and replace of all occurrences.
The only solution I’ve found so far is using dynamic SQL and concatenating the string like this example:
SET @s = CONCAT('select * from ', @Cat, ' where ID = ', @ID_1);
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
Is there an easier way?
Cheers, Lucas