简体   繁体   中英

How to get a row by ID in a MySQL Stored Procedure?

I have a problem with a Stored Procedure in MySQL. I want to get a single row by passing the ID parameter, however, it seems the SP ignores the WHERE filter and displays all the columns of the table.

What I find strange is that if I pass a specific value for id in a query outside the stored procedure, for example 1003, returns the expected result.

Sorry if my mistake is silly, I'm newbie.

The table structure is something like this:

CREATE TABLE Paciente
 (
    ID INT AUTO_INCREMENT NOT NULL,
    DNI CHAR(8) UNIQUE NULL,
    Nombre NVARCHAR(70) NOT NULL,
    Apellido_Paterno NVARCHAR(30) NOT NULL,
    Apellido_Materno NVARCHAR(30) NOT NULL,
    Edad TINYINT NOT NULL,
    Sexo CHAR(1) NOT NULL,
    Calle NVARCHAR(50) NULL,
    Numero_Domicilio SMALLINT(4) NULL,
    Telefono NVARCHAR(8) NULL,
    Movil NVARCHAR(10) NULL,
    Estado_Civil NVARCHAR(20) NULL,
    Ocupacion NVARCHAR(30) NULL,
    Fecha_Registro DATETIME DEFAULT CURRENT_TIMESTAMP,
    Estado BOOLEAN NULL DEFAULT TRUE,
    PRIMARY KEY(ID)
)ENGINE = InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1000;


Stored Procedure:

DELIMITER $$
CREATE PROCEDURE `buscarPaciente`(IN id INT)
BEGIN
SELECT * FROM Paciente WHERE ID = id LIMIT 1;
END
$$
DELIMITER ;

The behaviour is caused by naming the input parameter same as the column name, therefore mysql cannot distinguish between the column and the parameter within the where clause. Rename the input parameter to let's say param_ID and it will return the record with the requested ID value.

DELIMITER $$
CREATE PROCEDURE `buscarPaciente`(IN param_ID INT)
    BEGIN
        SELECT * FROM Paciente WHERE ID = param_ID LIMIT 1;
    END
$$
DELIMITER ;
DELIMITER $$                                                                           
CREATE PROCEDURE `Student`(IN param_ID INT)                                                
   BEGIN                                                                                      
       SELECT * FROM Student WHERE **Student.ID = param_ID** LIMIT 1;                       
   END                                                                
$$                                                                     
DELIMITER ;

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