MariaDB: How to store a Table name into a variable? - mysql

I need to use multiple times a table name into a query. To avoid repeating it I want to store the name into a User-Defined Variable.
What is wrong with this query?
SET #tableName := 'de-Table'
SELECT * FROM #tableName;
In MariaDB the error is cryptic and (as usual) doesn't help at all:
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM #tableName' at line 3 */
Thank you in advance

You need to use dynamic MySQL if you want a variable to be the table name. The following should work, if you're doing this directly from MySQL:
SET #tableName = 'de-Table';
SET #query = CONCAT('SELECT * FROM ', #tableName);
PREPARE stmt FROM #query;
EXECUTE stmt;

Related

Dynamic SQL on mySQL 8

The plan is to construct a dynamic sql that will execute create view statements. We have multiple servers but the schemas are the same across all servers.
I have started off with the following,
set #businessId = 'buName-1234.';
SET #table_name:= concat(#businessId,'Test');
SELECT #table_name;
SET #sql:=CONCAT('SELECT * FROM ',#table_name);
SELECT #sql;
which gives the output as,
SELECT * FROM buName-1234.Test
The issue arises on the execution part,
PREPARE dynamic_statement FROM #sql;
EXECUTE dynamic_statement;
DEALLOCATE PREPARE dynamic_statement;
The error is,
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-1234.Test' at line 1
I have tried changing the single quote set #businessId = 'buName-1234.'; to a backtick, but that also fails with error,
Error Code: 1054. Unknown column 'buName-1234.' in 'field list'
The error can't be replicated on dbfiddle
Concatenating backticks to the server name is the way to do this in my case, like so,
SET #databaseName= 'buName-1234';
SET #table = 'Test';
SET #fullTable_name:= concat("`",#databaseName,"`.",#table);
SET #sql:= CONCAT('SELECT * FROM ',#fullTable_name,";");
SELECT #sql
which give the output as,
SELECT * FROM `buName-1234`.Test;
which can be used in PREPARE & EXECUTE.

MySQL SQL syntax error near '0' at line 1

I have tried various modifications to make this work but I can't seem to remove the error. My SQLQuery string is much larger than the one below but same set up. I tried using a CONCAT(' ') statement but had issues. So I tried using this format but still receive the same error. any suggestions?
CREATE DEFINER=`root`#`%` PROCEDURE `stp_Select_GetTbl`(IN strWhereClause
VARCHAR(255))
BEGIN
DECLARE SQLQuery varchar(1000);
SET SQLQuery = '
SELECT `Part Num` AS `PPNumber`,
`Shop Num` as `SOrder`
FROM `track`.`s list` WHERE ';
SET #SQLQuery = #SQLQuery + strWhereClause + '';
PREPARE stmt FROM #SQLQuery;
EXECUTE stmt;
END
ERROR:
`Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0' at line 1
`
I have tried not declaring SQLQuery... changing varchar size... reorganizing and even using the example below
SET #getList =
CONCAT('SELECT (t1, t2, t3) FROM (SELECT t1, t2, t3) as mainSelect WHERE ', strWhereClause, '');
PREPARE stmt FROM #getList;
EXECUTE stmt;
END
but get error at
.... MySQL server version for the right syntax to use near '0
I need to define a string for my SELECT statement because I create the WHERE clause in my stored procedure.

How do you use user variables in Mysql If clause?

I want to alter a table and add a column to it if it doesn't already exist. So I populate a variable #row and if it's I want to alter the able as so.
SET #row = (SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_NAME='tblname' AND COLUMN_NAME='colname' and table_schema='dbname');
IF(#row <1) THEN
ALTER TABLE tblname ADD colname INT;
END IF;
But I am getting a syntax error
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near 'IF(#row <1) THEN ALTER TABLE tblname ADD colname INT' at line 1
What am I doing wrong?
In MySQL you need a shell around flow statements like if.
Put a procedure around it and it will work.
You can use prepared statements
IF (#row <1) THEN
SET #lSQL = "ALTER TABLE tblname ADD colname INT";
PREPARE stmt FROM #lSQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
Hope it helps.

MySQL Stored Procedure with Prepared Statement does not work

I have the following stored procedure:
CREATE PROCEDURE getLastValueAutomaticShelter(IN fieldName varchar(30), position_number INT)
BEGIN
SET #query = CONCAT('SELECT * FROM automatic_changes WHERE',fieldName,'IS NOT NULL AND P_id=?');
PREPARE stmt FROM #query;
SET #position_number=position_number;
EXECUTE stmt USING #position_number;
DEALLOCATE PREPARE stmt;
END
Then I am running it:
mysql> call getLastValueAutomaticShelter('current_level', 500)//
And getting the following error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'NOT N
ULL AND P_id=?' at line 1
Any ideas? Thanks.
You need to add some spaces in there:
SET #query = CONCAT('SELECT * FROM automatic_changes WHERE ',fieldName,' IS NOT NULL AND P_id=?');
/* right ^ here....and ^ here*/
Otherwise your final query might look like this:
SELECT * FROM automatic_changes WHEREcolumnameIS NOT NULL AND P_id='whatever';
You get the idea :)

MySQL Prepare statement syntax

I am having trouble getting my prepare statement to run in MySQL 5.6.14; here is the block of code in question:
SET #backupDate = DATE(NOW());
SET #renameTable = CONCAT('RENAME TABLE activeDirectoryData TO actDirBackup-', #backupDate);
PREPARE goRenameTable FROM #renameTable;
EXECUTE goRenameTable;
DEALLOCATE PREPARE goRenameTable;
The script stops at the prepare statement, with the following error:
Error Code: 1064. You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '-2013-11-06' at line 1
Any idea what is wrong here?
The name actDirBackup- with the value coming from #backupDate isn't a valid table name, you have to escape it, something like this:
SET #renameTable = CONCAT('RENAME TABLE activeDirectoryData TO `actDirBackup-',
#backupDate, '`');