SQL Stored Procedure - Run a SQL Query - mysql

Here is the way I am creating my stored procedure:
SET #SQL =
(SELECT ddl_script FROM TABLENAME.versions where ID = 5)
;
USE TABLENAME;
DROP procedure IF EXISTS `ddl_stored_procedure`;
DELIMITER $$
CREATE PROCEDURE `ddl_stored_procedure` ()
BEGIN
PREPARE part1 FROM #SQL;
EXECUTE part1;
DEALLOCATE PREPARE part1;
END$$
DELIMITER ;
This part works fine and my stored procedure is created. Now I try to run my stored procedure with this line of code to test it:
CALL `DBNAME`.`ddl_stored_procedure`();
And I get the error message:
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 'USE `xxx_landing`; CREATE TABLE `TABLE1` ( `ROW1` varchar(1), `T' at line 1
The code that is running, is an SQL statement inside one of my databases as longtext and looks like this:
CREATE DATABASE `xxx_landing` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `xxx_landing`;
CREATE TABLE `TABLE1` (
`ROW1` varchar(1),
`ROW2` varchar(20),
`ROW3` varchar(3)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `TABLE2` (
`ROW4` varchar(2),
`ROW5` varchar(10),
`ROW6` varchar(10),
`ROW7` varchar(10),
`ROW8` varchar(10),
`ROW9` varchar(50)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
I do not know why the stored procedure fails to create the database, use it and create all tables. If I execute the SQL-Query manually there is no syntax error.
Can someone explain me what I am doing wrong?
Thanks in advance!

Related

Prepared Statement get wrong result in MYSQL

I have a table with design
CREATE TABLE IF NOT EXISTS InsuranceContract (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`enquiryCode` VARCHAR(20) DEFAULT NULL,
`contractCode` VARCHAR(20) DEFAULT NULL,
`createdAt` DATETIME DEFAULT CURRENT_TIMESTAMP (),
`updatedAt` DATETIME DEFAULT CURRENT_TIMESTAMP () ON UPDATE CURRENT_TIMESTAMP (),
UNIQUE KEY (`enquiryCode`)) ENGINE=INNODB DEFAULT CHARSET=UTF8 COLLATE = UTF8_BIN;
Then I was created a procedure like this
DROP procedure IF EXISTS `sp_insurance_contract_get`;
DELIMITER $$
CREATE PROCEDURE `sp_insurance_contract_get` (enquiryCode VARCHAR(20), contractCode VARCHAR(20))
BEGIN
SET #t1 = "SELECT * FROM InsuranceContract
WHERE InsuranceContract.enquiryCode = enquiryCode
AND InsuranceContract.contractCode = contractCode;";
PREPARE param_stmt FROM #t1;
EXECUTE param_stmt;
DEALLOCATE PREPARE param_stmt;
END$$
DELIMITER ;
And I was executed this procedure in MySQL Workbench by this command:
CALL sp_insurance_contract_get('EQ000000000014', '3001002');
I expected I will receive 1 row result but it selected all records in this table.
If I copy and create exactly this #t1 into plain SQL not using statement, it's correct.
Please help me to fix this error. I'm using MySQL 8.0.19
You can use placehoders on prepare statements, this is why we use them to prevent sql injection
One other thing never use column names as variables names, databases can not differentiate
DROP procedure IF EXISTS `sp_insurance_contract_get`;
DELIMITER $$
CREATE PROCEDURE `sp_insurance_contract_get` (enquiryCode_ VARCHAR(20), contractCode_ VARCHAR(20))
BEGIN
SET #t1 = "SELECT * FROM InsuranceContract
WHERE enquiryCode = ?
AND contractCode = ?;";
PREPARE param_stmt FROM #t1;
SET #a = enquiryCode_;
SET #b = contractCode_;
EXECUTE param_stmt USING #a, #b;
DEALLOCATE PREPARE param_stmt;
END$$
DELIMITER ;
When you say
WHERE enquiryCode = enquiryCode
you compare that named column to itself. The result is true always (unless the column value is NULL).
Change the names of your SP's parameters, so you can say something like
WHERE enquiryCode_param = enquiryCode
and things should work.
Notice that you have no need of a MySql "prepared statement" here. In the MySql / MariaDb world prepared statements are used for dynamic SQL. That's for constructing statements within the server from text strings. You don't need to do that here.

MySQL Syntax Error With Stored Procedures

I must be missing something simple because I can't figure out what is causing my script to fail.
Below is the stored procedure I've written:
CREATE PROCEDURE `Search_contacts`(IN `in_owner_id` INT,
IN `in_first_name` VARCHAR(255))
IF in_first_name IS NOT NULL THEN
SELECT * FROM `contacts`
WHERE `owner_id` = in_owner_id AND `first_name` LIKE in_first_name;
END IF;
When I try and execute this on my MySQL server I get the following 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 '' at line 5
I'd like to know what is causing this error and why so I can avoid it again.
Any help is appreciated!
Try adding "BEGIN", "END" and "DELIIMITER", like this:
DELIMITER $$
CREATE PROCEDURE `Search_contacts`(IN `in_owner_id` INT,
IN `in_first_name` VARCHAR(255))
BEGIN
IF in_first_name IS NOT NULL THEN
SELECT * FROM `contacts`
WHERE `owner_id` = in_owner_id AND `first_name` LIKE in_first_name;
END IF;
END $$
DELIMITER ;

When I create a variable in create procedure on mySQL I get an error

//This is the code
create procedure st_insertRole(
#name varchar(30) //I get the error here
as
insert into roles values(#name)
);
here is the screenshot
My SQL does not allow session variables to be used for procedure parameters. You also have parentheses misplaced. The code in MySQL would look more like:
delimiter $$
create procedure st_insertRole (
in_name varchar(30)
)
begin
insert into roles (name)
values (in_name);
end; $$
The syntax is wrong
create procedure st_insertRole(
name_ varchar(30) )
insert into roles values(name_)
;

Drop procedure if exists in mysql

Hi i am trying to create a mysql script that I can run whenever I need to update my database. The script creates a table and then executes some stored procedures.
DELIMITER $$
CREATE TABLE IF NOT EXISTS tbl_name (
col1 bigint(20) NOT NULL AUTO_INCREMENT,
col2 varchar(255) NOT NULL,
col3 varchar(64) NOT NULL,
col4 datetime DEFAULT NULL,
PRIMARY KEY (`col1 `),
UNIQUE KEY col2 (`col2`)
) ENGINE=InnoDB AUTO_INCREMENT=572 DEFAULT CHARSET=utf8$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `myproc`(IN username
VARCHAR(255))
BEGIN
DECLARE var1 VARCHAR(64);
DECLARE expirationDate DATETIME;
SET var1 = 12345;
SET expirationDate = DATE_ADD(NOW(), INTERVAL 30 SECOND);
REPLACE INTO tbl_name (col2, col3, col4) VALUES (someval, var1, expirationDate);
END$$
DELIMITER ;
When I ran the script first time, it created the table and executed the stored procedure in MySQL Workbench. When I ran the same thing second time, I got the error 1304 procedure already exists.
I looked online here about dropping the procedure and then create again. But when I entered the below command before creating the procedure, i got an error on CREATE command with code 1064.
DROP PROCEDURE IF EXISTS myproc;
CREATE DEFINER=`root`#`localhost` PROCEDURE `myproc`(IN username
VARCHAR(255))
.
.
.
I am very new to mysql and not sure how to execute the procedure if it already exists.
Any help would be appreciated.
Since you changed to DELIMITER $$ you need to use that delimiter at the end of each statement until you change it back.
DROP PROCEDURE and CREATE PROCEDURE are separate statements, and each requires its own statement delimiter.
DROP PROCEDURE IF EXISTS myproc $$
Note the delimiter at the end of the line above.
CREATE DEFINER=`root`#`localhost` PROCEDURE `myproc`(IN username
VARCHAR(255))
.
.
.
END $$
And another delimiter at the end of the whole CREATE PROCEDURE statement.

MariaDB stored proc - Getting an error 'Missing SELECT' on INSERT statement

While I created loads of procs in SQL server, I want to start using MariaDB and so tried creating the simple proc below in MySQL Workbench.
I keep on getting an error stating that there is a missing SELECT on the opening '(' after the table name:
DELIMITER $$
drop procedure if exists usp_AddSentEmail$$
CREATE PROCEDURE usp_AddSentEmail (in pSender varchar(36)
,in pTo varchar(1000)
,in pSubject varchar(100)
,in pBody varchar(10000)
,in pRecordDT datetime)
BEGIN
INSERT INTO Emails('To','Subject','Body','Sender','RecordDT','Sent','SentDT')
VALUES (pTo,pSubject,pBody,pSender,pRecordDT,1,pRecordDT);
END$$
DELIMITER ;
Maybe I am trying the wrong google search but that all comes up is delimiter errors.
remove the quotes from the column names in your insert query:
INSERT INTO Emails(To,Subject,Body,Sender,RecordDT,Sent,SentDT)
VALUES (pTo,pSubject,pBody,pSender,pRecordDT,1,pRecordDT);