Prepared Statement get wrong result in MYSQL - 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.

Related

How can i define variable for default values in MariaDB structure?

I need to change a lot default values of the DB structure for new entries in MULTIPLE tables to have this new default value in DB I tried to use something like this:
SET #money_rename_def := 20*10000;
SET #money_gender_def := 40*10000;
ALTER TABLE `money` CHANGE `money_rename` `money_rename` int(10) UNSIGNED NOT NULL DEFAULT '#money_rename_def',
CHANGE `money_gender` `money_gender` int(10) UNSIGNED NOT NULL DEFAULT '#money_gender_def';
But the SET prefix does not fork for alter table command. Is there any way how to do this to use pre-defined value so I can only change it once in SET or simillar definition?
I tried to search documentation but maybe just missed it?
You can use dynamic query like this:
DROP PROCEDURE IF EXISTS `tableDefaultSetter`$$
CREATE PROCEDURE `tableDefaultSetter`()
BEGIN
SET #default1 = 20;
SET #query = concat('ALTER TABLE `ttestt` CHANGE `val` `val` int NOT NULL DEFAULT ', #default1);
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
Sample Data:
DROP TABLE IF EXISTS ttestt;
CREATE TABLE ttestt
(
id INT,
val INT(10) DEFAULT 10
);
INSERT INTO ttestt (id)
VALUES (1);
CALL tableDefaultSetter();
INSERT INTO ttestt (id)
VALUES (1);
SELECT *
FROM ttestt;
Result:
1,10
1,20
So the first item had 10 as default value and second item has been changed to 20. You see that it works.
For multiple values, you cannot put multiple queries inside one statement:
Doc
The text must represent a single statement, not multiple statements.
So you can create another procedure for convenience:
DELIMITER $$
DROP PROCEDURE IF EXISTS `exec_query`$$
CREATE PROCEDURE `exec_query`(queryStr TEXT)
BEGIN
SET #query = queryStr;
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DROP PROCEDURE IF EXISTS `tableDefaultSetter`$$
CREATE PROCEDURE `tableDefaultSetter`()
BEGIN
SET #default1 = 20;
SET #default2 = 30;
SET #default3 = 40;
SET #default4 = 50;
CALL exec_query(concat('ALTER TABLE `ttestt` CHANGE `val` `val` int NOT NULL DEFAULT ', #default1));
CALL exec_query(concat('ALTER TABLE `ttestt2` CHANGE `val` `val` int NOT NULL DEFAULT ', #default2));
CALL exec_query(concat('ALTER TABLE `ttestt3` CHANGE `val` `val` int NOT NULL DEFAULT ', #default3));
CALL exec_query(concat('ALTER TABLE `ttestt4` CHANGE `val` `val` int NOT NULL DEFAULT ', #default4));
END$$
DELIMITER ;
Use it like this:
CALL tableDefaultSetter();
DROP PROCEDURE `tableDefaultSetter`;
DROP PROCEDURE `exec_query`;

SQL Stored Procedure - Run a SQL Query

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!

How to use mysql unix_timestamp() as the starting point for auto increment?

I would like to know if it is possible do create a table having the auto increment start with the value of the unix timestamp (the time of create of the table), i.e.
create table something(
something_id bigint not null primary key auto_increment,
something_name varchar(10) not null,
something_random varchar(3) not null
) engine=InnoDB auto_increment=round(unix_timestamp(curtime(4)) * 1000);
Note that I can just replace auto_increment=round(unix_timestamp(curtime(4)) * 1000) with the value of select round(unix_timestamp(curtime(4)) * 1000);. But what I want is a way to do it automatically when creating my tables.
After reading mysql select section everything I tried gave me a compiler error.
Thanks.
One way could be to use a stored procedure that does this.
Procedure that receives the table creation command and concatenates (CONCAT function) the value of the expression at the end. Since the query is in string format, the Prepared Statement is used to execute it.
DELIMITER $$
DROP PROCEDURE IF EXISTS `createTable`$$
CREATE PROCEDURE createTable(IN strCreateQuery TEXT)
BEGIN
SET #query = CONCAT(strCreateQuery, " auto_increment=", ROUND(UNIX_TIMESTAMP(CURTIME(4)) * 1000));
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
Once created, simply execute the procedure with the creation query of the desired table.
CALL createTable("
create table something(
something_id bigint not null primary key auto_increment,
something_name varchar(10) not null,
something_random varchar(3) not null
) engine=InnoDB");

Scheduling A Weekly Script for rebuild Mysql Index

We are planning to deploy a Stored Procedure to rebuild index. As per below specifictions on Mysql forum. Someone can send any sample script do the same for all table in a particular Database. Will there is any concern or any issues we could face for below script running on weekend.
ALTER TABLE t1 ENGINE = InnoDB;
https://dev.mysql.com/doc/refman/5.7/en/rebuilding-tables.html#rebuilding-tables-alter-table
Index's are kept up to date in InnoDB, statistics can get out of date. Post 5.6 even that is rarely needed to my knowledge. Running the Alter command will repair the table, which will repair any fragmentation. You can read about the different types of algorithms that are available to ALTER TABLE here:
ALTER TABLE
If however you want to check the database over, you can use the check mysql command which does ALTER as well as a few other bits n pieces to optimise index's, update statistics etc.
mysqlcheck
Below is a the mysql script to Optimize the Mysql DB. However as said earlier its rarely required since InnoDB is itself able to do the same.
USE VIPLamar;
DROP PROCEDURE IF EXISTS Lamar_Index_Rebuild_Script;
DELIMITER //
-- call Lamar_Index_Rebuild_Script();
CREATE PROCEDURE Lamar_Index_Rebuild_Script()
mysp:BEGIN
Declare v_max_counter int;
Declare v_counter int;
Declare v_query longtext;
Declare v_table_name varchar(1000);
Declare v_datetime datetime default now();
DROP temporary TABLE if exists temp_todo;
create temporary table temp_todo
(
id int auto_increment primary key,
`table_name` varchar(1000)
);
create table if not exists VIP_Lamar_Index_Rebuild_Script
(
id int auto_increment primary key,
`table_name` varchar(1000),
start_date datetime,
finish_date datetime
);
insert into temp_todo (table_name)
SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = DATABASE();
-- loop thru table
-- check if table exists
Select max(id) Into v_max_counter from temp_todo;
Set v_counter = 1;
WHILE v_counter <= v_max_counter
Do
select `table_name` into v_table_name from temp_todo where id = v_counter;
IF (EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE table_name = v_table_name AND table_schema = DATABASE()))
THEN
set v_query = concat('OPTIMIZE TABLE ' , v_table_name , ';');
set #stmt = v_query;
PREPARE tempstatement FROM #stmt;
EXECUTE tempstatement;
DEALLOCATE PREPARE tempstatement;
END if;
set v_counter = v_counter +1 ;
end while;
insert into VIP_Lamar_Index_Rebuild_Script(`table_name`,start_date,finish_date)
select table_name,v_datetime,now() from temp_todo
;
-- select * from VIP_Lamar_Index_Rebuild_Script;
-- drop table VIP_Lamar_Index_Rebuild_Script;
DROP temporary TABLE if exists temp_todo;
END;
//
DELIMITER ;

How do I modify a MySQL column to allow NULL without specifying its data type?

I have a table in mysql and I want to alter a table to allow a column to be null.
When I do describe on my mysql table, I see these things in mysql workbench:
Field Type Null Key Default Extra
I want to set Null field as YES for a particular column. Here is how I am trying which works fine but do I need to provide its data type while setting DEFAULT to NULL?
ALTER TABLE abc.xyz CHANGE hello hello int(10) unsigned DEFAULT NULL;
ALTER TABLE abc.xyz CHANGE world world int(10) unsigned DEFAULT NULL;
Is there any other way by which I can just pick column name and set default to NULL instead of using its data type as well? I don't want to provide int(10) while setting its default to NULL.
You're kind of on the wrong track. Changing the default to NULL does not "allow" the column to be null: what you need to do is drop the "NOT NULL" constraint on the column.
But to redefine the nullability of a column through script, you will have to continue to reference the datatype. You'll have to enter something like
ALTER TABLE MyTable MODIFY COLUMN this_column Int NULL;
Not sure if this applies if you're looking for a straight DDL statement, but in MySQL Workbench you can right-click on a table name, select "Alter Table..." and it will pull up a table definition GUI. From there, you can select null/not null (among all the other options) without explicitly listing the column's datatype. Just a "for what it's worth"...
This can be done with the help of dynamic statements.
Usage:
CALL sp_make_nullable('schema_name', 'table_name', 'column_name', TRUE);
Implementation:
DELIMITER $$
create procedure eval(IN var_dynamic_statement text)
BEGIN
SET #dynamic_statement := var_dynamic_statement;
PREPARE prepared_statement FROM #dynamic_statement;
EXECUTE prepared_statement;
DEALLOCATE PREPARE prepared_statement;
END;
DELIMITER ;
DELIMITER $$
create procedure sp_make_nullable(IN var_schemaname varchar(64), IN var_tablename varchar(64),
IN var_columnname VARCHAR(64), IN var_nullable BOOLEAN)
BEGIN
DECLARE var_column_type LONGTEXT DEFAULT (SELECT COLUMN_TYPE
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = var_schemaname
AND TABLE_NAME = var_tablename
AND COLUMN_NAME = var_columnname);
DECLARE var_nullable_prefix VARCHAR(64) DEFAULT '';
IF NOT var_nullable THEN
SET var_nullable_prefix := 'NOT';
end if;
CALL eval(CONCAT('
ALTER TABLE ', var_schemaname, '.', var_tablename,
' MODIFY ', var_columnname, ' ', var_nullable_prefix, ' NULL
'));
end$$
DELIMITER ;