简体   繁体   中英

Syntax Error in MySQL stored procedure

The below SP is not giving any result even though there are 48 rows as per the where clause

BEGIN
DECLARE SelectClause VARCHAR(2000);
  if v_mode='SearchByString' then
    SET SelectClause ='select SURVEY_USER.username,SURVEY.* from SURVEY, SURVEY_USER';

if v_SearchString is not null then
    SET SelectClause=CONCAT(@SelectClause,'  where ');
    Set SelectClause=CONCAT(@SelectClause,v_SearchString);
end if;
SET SelectClause=CONCAT(@SelectClause,'  order by SURVEY.created_date DESC;') ;
select SelectClause;
SET @query = SelectClause;
    PREPARE stmt FROM  @query;
    EXECUTE stmt;
 select stmt;
end if;
END

I tried a lot but not getting any problem. I also tried select clause to print the command at various places to not able to print it. Please give me some solution. There are my parameters that I am passing v_mode='SearhByString' v_SearchString='SURVEY_USER.username=chiragfanse'

It should return 48 rows but does not return anything.

BEGIN

  DECLARE SelectClause VARCHAR(2000);

  IF v_mode = 'SearchString' THEN

    SET SelectClause = CONCAT('select SURVEY_USER.username,SURVEY.* from SURVEY, SURVEY_USER');

    IF SearchString IS NOT NULL THEN
      SET SelectClause = CONCAT(SelectClause, ' where ', SearchString);
    END IF;

    SET SelectClause = CONCAT(SelectClause, '  order by SURVEY.created_date DESC;');

    SET @query = SelectClause;
    PREPARE stmt FROM  @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

  END IF;
END
  1. All declaration have to be at the begining.
  2. Rename @SelectClause to SelectClause, because you are declaring this variable.
  3. Check the usage of SET clauses. I have added one.
  4. Have a look at prepared statements reference, it will help you to execute the query you built.

you have wrong concat functions. Try this.

if v_mode='SearchString' then
DECLARE @SelectClause varchar(2000);
SET @SelectClause =CONCAT(select (SURVEY_USER.username,SURVEY.*) from SURVEY, 'SURVEY_USER');
if SearchString is not null then
@SelectClause=CONCAT(@SelectClause, 'where' ,SearchString);
end if;
SET @SelectClause=@SelectClause
order by SURVEY.created_date DESC
execute(@SelectClause)
end if;

try this. let me know if you need anything else.

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