My SQL Dynamic query execute and get ouput into a variable in stored procedure

前端 未结 2 638
小鲜肉
小鲜肉 2020-12-01 10:05

I generate a dynamic query in My sql Stored procedure. I wanna get the result of this query into a out parameter. How to do this ?

CREATE PROCEDURE \'searchI         


        
相关标签:
2条回答
  • 2020-12-01 10:32

    Have a look at this example -

    CREATE TABLE table1(
      column1 VARCHAR(255) DEFAULT NULL,
      column2 VARCHAR(255) DEFAULT NULL,
      column3 VARCHAR(255) DEFAULT NULL
    );
    
    INSERT INTO table1 VALUES 
      ('1', 'value1', 'value2'),
      ('2', 'value3', 'value4');
    
    DELIMITER $$
    CREATE PROCEDURE procedure1(IN Param1 VARCHAR(255), OUT Param2 VARCHAR(255), OUT Param3 VARCHAR(255))
    BEGIN
      SET @c2 = '';
      SET @c3 = '';
      SET @query = 'SELECT column2, column3 INTO @c2, @c3 FROM table1 WHERE column1 = ?';
      PREPARE stmt FROM @query;
      SET @c1 = Param1;
      EXECUTE stmt USING @c1;
      DEALLOCATE PREPARE stmt;
      SET Param2 = @c2;
      SET Param3 = @c3;
    END$$
    DELIMITER ;
    
    -- Call procedure and use variables
    SET @Param1 = 2;
    SET @Param2 = '';
    SET @Param3 = '';
    CALL procedure1(@Param1, @Param2, @Param3);
    SELECT @Param2, @Param3;
    +---------+---------+
    | @Param2 | @Param3 |
    +---------+---------+
    | value3  | value4  |
    +---------+---------+
    
    0 讨论(0)
  • 2020-12-01 10:36
    select count(*) into @numOfRecords from .... 
    

    You have do declare the variable within stored procedure

    I hope I've understood your question.

    0 讨论(0)
提交回复
热议问题