简体   繁体   中英

Storing a field in a variable in stored procedure

DELIMITER $$

DROP PROCEDURE IF EXISTS `ecview_1_10_siruseri`.`test` $$
CREATE DEFINER=`super`@`%` PROCEDURE `test`(In MeterThreadName varchar(30))
BEGIN

Declare MeterThreadId int;

select last_processed_time,meterthreadid=meter_thread_id from meter_thread where name =MeterThreadName;


select ems_device_name, meter_parameter_type_map_id from ems_device e
join meter_parameter_type_map mp on e.meter_id = mp.meter_id and mp.meter_thread_id = meterThreadID;


END $$

DELIMITER ;

I am trying to store the field in a variable meterthreadid=meter_thread_id and then using it in another query ,But all I am getting is the null value for meter_thread_id ..

Let me know if the procedure is wrong anywhere ??

Thanks

The = just checks for equality. The assignment operator is := . Though you better write it like

SELECT 'whatever' INTO variable_name FROM table;

Not sure from the top of my head, if the assignment operator is restricted to user-defined variables (the ones beginning with an @ ).

What you should also keep in mind is, that the variable will hold the value of the last row the select fetched, not from every row. Your procedure all in all is quite...well, the programmers would call it undefined behaviour .
Add an ORDER BY clause (preferably with a LIMIT ) or make sure that your WHERE clause restricts the result to one row.

All in all I wonder, what your procedure actually is any good for. You could as well just do it all in one SELECT statement.

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