Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql query help (like statement)

I am using mysql which i have a stored procedure which has an input variable.

I want to use this variable in a select statement (with like clause).

Eg:

DELIMITER $$

DROP PROCEDURE IF EXISTS `DeleteDataByTransactionID` $$
CREATE DEFINER=`root`@`%` PROCEDURE `DeleteDataByTransactionID`(in **$TransactionID** varchar(50))

BEGIN

delete from sqlstatements where tempsql like '%'+ **$TransactionID** + '%';

END $$


DELIMITER ;

Thanks

like image 299
David Bonnici Avatar asked Feb 13 '26 07:02

David Bonnici


2 Answers

DELIMITER $$
DROP PROCEDURE IF EXISTS `DeleteDataByTransactionID`
$$
CREATE DEFINER=`root`@`%` PROCEDURE `DeleteDataByTransactionID`(TransactionID VARCHAR(50))
BEGIN
        DELETE
        FROM    sqlstatements
        WHERE   tempsql LIKE CONCAT('%', TransactionID, '%');
END
$$
DELIMITER ;
like image 164
Quassnoi Avatar answered Feb 15 '26 23:02

Quassnoi


Actually, the accepted answer's version is open to SQL injection if the caller does not properly parameterize the call to the stored procedure. I would recommend utilizing a prepared statement in the stored procedure as follows to be safe instead of relying on the caller:

DELIMITER $$
CREATE PROCEDURE `DeleteDataByTransactionID`
(
    TransactionID VARCHAR(50)
)
BEGIN

SET @sql = 
 "DELETE 
  FROM sqlstatements
  WHERE   
     tempsql LIKE CONCAT('%', ?, '%')";

SET @transid  = TransactionID;

PREPARE stmt FROM @sql;
EXECUTE stmt USING @transid;
DEALLOCATE PREPARE stmt;

END
$$

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!