I have a case where getting the Table name should be from a Set Variable like :

SET @ID_1 = (SELECT ID FROM `slider` LIMIT 0,1);
SET @Cat = (SELECT Category FROM `slider` LIMIT 0,1);
select * from @Cat where ID = @ID_1

but doing that way MySQL output's and error ,so could someone point me how can i Achieve that ,because these are my baby steps to MySQL

share|improve this question
up vote 57 down vote accepted

You'd have to do this with a prepared statement. Something like:

SET @s = CONCAT('select * from ', @Cat, ' where ID = ', @ID_1); 

PREPARE stmt1 FROM @s; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1; 
share|improve this answer
    
One more thing it show resul only when i remove DEALLOCATE PREPARE stm1; – Burimi Jan 10 '12 at 20:37
    
Brilliant solution. Helped me to solve the issue I'm having, thanks. – Tim Visée May 26 '16 at 12:36
    
What does the DEALLOCATE PREPARE do? – Frozen Flame Jun 29 '16 at 2:59
    
@FrozenFlame, release the stmt1. If you do not release it, may you encounter the max limit of statements, enforced by max_prepared_stmt_count variable system, how you can read here. – ruzenhack Jul 12 '17 at 19:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.