is it possible to insert into a MySQL table with the whole VALUES block of code being a parameter?
Parameter would be:
("(638) 833-5496","enim.curabitur#hotmail.couk","Spain"),
("(293) 742-0229","odio.semper#yahoo.net","Belgium"),
("1-265-156-4304","tincidunt.dui.augue#outlook.net","Ireland"),
("1-833-780-2553","scelerisque.scelerisque#aol.com","France"),
("(619) 691-0656","ac.risus.morbi#icloud.org","Costa Rica");
Insert statement would be
INSERT INTO `myTable` (`phone`,`email`,`country`)
VALUES
{parameter}
Is it possible to do as an Insert statement, stored procedure, or anything?
I was able to solve this by utilizing the EXECUTE command and passing the string as a variable and then compiling it into one SQL statement.
CREATE DEFINER=`admin`#`%` PROCEDURE `insert_string_storedprocedure`(bubble_variable text)
BEGIN
set #insert_string = "INSERT INTO `myTable`
(`phone`,`email`,`country`)
VALUES
(insert_statement)
AS new
ON DUPLICATE KEY UPDATE
email = new.email;";
set #fullcommand = REPLACE(#insert_string, '(insert_statement)', bubble_variable);
PREPARE stmt FROM #fullcommand;
EXECUTE stmt;
END
Related
This sp generate this Error but when I get the #queryString value and execute it, It's working:
Query 1 ERROR: 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 'CREATE TRIGGER triggers_after_insert AFTER INSERT ON mydb.mytable F' at line 2
This error is generated when I execute:
CALL prcTriggersLogsRefreshFields('mydb','mytable','myidtable');
This is the code:
DROP PROCEDURE "prcTriggersLogsRefreshFields";
CREATE PROCEDURE "prcTriggersLogsRefreshFields"(
par_dbName text,
par_tableName text,
par_keyField text
)
BEGIN
SET #strJsonObj = null;
SET #change_object = par_dbName||'.'||par_tableName;
SELECT GROUP_CONCAT('\'',COLUMN_NAME, '\',', COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = par_dbName AND TABLE_NAME = par_tableName INTO #strJsonObj;
SET #queryString = 'DROP TRIGGER `triggers_after_insert`;
CREATE TRIGGER `triggers_after_insert` AFTER INSERT ON `'||par_dbName||'`.`'||par_tableName||'` FOR EACH ROW BEGIN
SELECT JSON_ARRAYAGG(JSON_OBJECT('||#strJsonObj||')) change_obj FROM `'||par_dbName||'`.`'||par_tableName||'` WHERE '||par_keyField||'=New.'||par_keyField||' INTO #jsonRow;
INSERT INTO mylog_db.table_log (`change_id`, `change_date`, `db_name`, `table_name`, `change_object`, `change_event_name`, `previous_content`, `change_content`, `change_user`) VALUES (DEFAULT, NOW(), '''||par_dbName||''', '''||par_tableName||''', '''||#change_object||''', \'insert\', \'{}\', #jsonRow, New.user_created);
END;';
-- select #queryString;
PREPARE stmt FROM #queryString;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html says:
SQL syntax for prepared statements does not support multi-statements (that is, multiple statements within a single string separated by ; characters).
You have to run the statements one at a time if you use PREPARE.
There's no need to include the DROP TRIGGER in your prepared statement. You can run the DROP TRIGGER without prepare & execute, since there is no dynamic part in it. Then format the CREATE TRIGGER as a single statement and prepare and execute it.
I have main_table:
SELECT PORT_ID, DATA from main_table
i need run trigger AFTER INSERT main_table which sort DATA to the other tables:
INSERT INTO #PORT_ID (DATA) VALUE (#DATA)
return an error message:
dynamic sql is not allowed in stored function or trigger resolved.
Any idea?
Many thanks
Workarround
I do a simply workarround, 1, save a SQL query into new table as a whole text. 2, run an EVENT per second with EXECUTE saved query
This is to big for a comment.
A simple Procedure that only executes the insert as prepared statement
CREATE DEFINER=`root`#`localhost` PROCEDURE `procedure_stmt`(IN test TEXT)
BEGIN
SET #sql = test;
PREPARE stmt2 FROM #sql;
EXECUTE stmt2;
END
ANd as a trigger
BEGIN
SET #sql = CONCAT('INSERT INTO ','gps_', NEW.PORT,' (DATA) VALUES (',NEW.DATTA,')');
CALL procedure_stmt(#sql);
END$$
DELIMITER ;
If you had posted tables and data i would have tested it further.
I have the following input of a list of clients I get from an external application that comes into a variable in a MySQL stored procedure such as this:
"2841,2212,1231,xxxx,...,1221"
...called input_clients
I want to take this list and insert it all in a temporary table with the field client_id.
I am wondering if someone can either point me to an existing script or show me how I can format this in a stored procedure that input so it will work as
INSERT INTO select_Clients(client_id) VALUES (input_client1), (input_client2)
because currently input_client stores all those clients in 1 string.
You can create a prepared statement inside the procedure as string and then execute it:
SET #input = '2841,2212,1231,1221';
DROP TEMPORARY TABLE IF EXISTS select_Clients;
CREATE TEMPORARY TABLE select_Clients(client_id INT);
SET #sql = CONCAT('INSERT INTO select_Clients(client_id) VALUES (', REPLACE(#input, ',', '),('), ')');
PREPARE stmt FROM #sql;
EXECUTE stmt;
http://rextester.com/FPDW88636
For some strange reason, inserting from stored procedure is not working.
This is what Im trying to do:
DROP TABLE IF EXISTS test;
CREATE TABLE IF NOT EXISTS test(
id INT(9) NOT NULL AUTO_INCREMENT
,name VARCHAR(30) NOT NULL
,PRIMARY KEY (id)
) DEFAULT CHARSET=utf8;
insert into test (name) values('A');
Inserting from command line works with no problems.
Then I created a stored procedure to do the same kind of insert:
DROP PROCEDURE IF EXISTS storedtest;
DELIMITER $$
CREATE PROCEDURE storedtest()
BEGIN
declare insert_sql varchar(200);
SET insert_sql = 'insert into test (name) values(3)';
SELECT insert_sql;
PREPARE mystm FROM #insert_sql;
EXECUTE mystm;
END$$
DELIMITER ;
call storedtest();
This gives me the error:
ERROR 1064 (42000): 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 'NULL' at line 1
NULL? Where did NULL came from?
I also tried changing the sql-insert to look like this (dont know if it is a good way):
SET insert_sql = "insert into test (name) values('3')";
But mysql gives me exactly the same error.
Anyone has a clue?
The NULL MySQL is reporting is an empty user variable #insert_sql, which is different from the local stored procedure local variable insert_sql which you allocated with DECLARE.
MySQL's DECLARE is used for variables local to a stored program, but according to the documentation, PREPARE stmt FROM ... expects either a string literal or a user variable, which are the type preceded with #.
PREPARE stmt_name FROM preparable_stmt
preparable_stmt is either a string literal or a user variable that contains the text of the SQL statement.
You can allocate the untyped user variable with SET so there is no need for DECLARE. You may wish to set it to NULL when you're finished.
DROP PROCEDURE IF EXISTS storedtest;
DELIMITER $$
CREATE PROCEDURE storedtest()
BEGIN
-- Just SET the user variable
SET #insert_sql = 'insert into test (name) VALUES (3)';
SELECT #insert_sql;
-- Prepare & execute
PREPARE mystm FROM #insert_sql;
EXECUTE mystm;
-- Deallocate the statement and set the var to NULL
DEALLOCATE PREPARE mystm;
SET #insert_sql = NULL;
END$$
DELIMITER ;
I have a stored procedure where I want to perform a INSERT operation. My INSERT query is stored in a php variable $query and I want to pass it as a parameter to my stored procedure.
$query_procedure = "CALL AddStation('$query','#LID')"
How can I get this query when I am creating the stored procedure?
Actually I want to use the same stored procedure for different INSERT queries
so that I dont have to pass individual parameters to the stored procedure.
Although you can technically achieve this, as shown below, I strongly discourage you from doing it. This a very bad idea. It simple doesn't make any sense and adds no value to your code. It's vulnarable to sql injections. You loose ability to use prepared statements for insert statements themselves. It's fragile and prone to errors since you're passing query strings, etc...
You better off without a stored procedure like this at all. Just use prepared statements in your client code.
DELIMITER$$
CREATE PROCEDURE AddARow(IN _sql TEXT, OUT _lid INT)
BEGIN
SET #sql = _sql;
PREPARE stmt FROM #sql;
EXECUTE stmt;
SET _lid = LAST_INSERT_ID();
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
Sample usage:
SET #lid = NULL;
SET #sql = 'INSERT INTO tablest (STATION_NAME, GEOGRAPHY) VALUES (''station1'',''India'')';
CALL AddARow(#sql, #lid);
SELECT #lid;
Here is SQLFiddle demo