简体   繁体   中英

SQL Stored Procedure String Search via Passed Parameter and Using 'LIKE' query

I am trying to create a stored procedure that will search my table using the parameter passed by the user as it calls the SP. I would like to use the 'LIKE' query for this. So far, this is what I got.

DROP PROCEDURE IF EXISTS `SEARCH_STUDENT`$$
CREATE
    PROCEDURE `test`.`SEARCH_STUDENT`(_textInput VARCHAR(10))
    BEGIN

    SELECT * FROM records WHERE `lastname` LIKE '%'+_textInput+'%';
    END$$

but im getting this 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 '@Search varchar(10);
    SET @Search=_textInput;
    SELECT * FROM records WHERE `last' at line 10

What I get from google are samples with fixed string to be searched. Mine depends on what the user will input in the textbox. Thanks a lot for any help in advanced.

I got it now. Thanks to this link.

http://www.sitepoint.com/forums/showthread.php?620319-MySQL-Stored-Procedure-LIKE-and-a-string-variable-the-combination-don-t-work

The sql CONCAT function is the answer. Here's my code now:

CREATE
    PROCEDURE `test`.`SEARCH_STUDENT`(_textInput VARCHAR(10))
    BEGIN

    -- sELECT * FROM records WHERE `lastname` LIKE '%' + _textInput;
    SELECT * FROM records WHERE `lastname` LIKE CONCAT('%',_textInput,'%');

    END$$
CREATE PROCEDURE `test`.`SEARCH_STUDENT`(in _textInput VARCHAR(10))
BEGIN
    -- SELECT * FROM records WHERE `lastname` LIKE '%' + _textInput;
    SELECT * FROM records WHERE `lastname` LIKE CONCAT('%',_textInput,'%');
END$$

put in

\`test\`.\`SEARCH_STUDENT\`(in _textInput VARCHAR(10))

other wise out will not show properly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM