Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MySQL: How to pass a table name as stored procedure and/or function argument?

For instance, this does not work:

DELIMITER // CREATE PROCEDURE countRows(tbl_name VARCHAR(40))   BEGIN     SELECT COUNT(*) as ct FROM tbl_name;   END //  DELIMITER ; CALL countRows('my_table_name'); 

Produces:

ERROR 1146 (42S02): Table 'test.tbl_name' doesn't exist 

However, this works as expected:

SELECT COUNT(*) as ct FROM my_table_name; 

What syntax is required to use an argument as a table name in a select statement? Is this even possible?

like image 627
randomx Avatar asked Jun 04 '10 19:06

randomx


People also ask

Can we pass table as parameter in stored procedure in MySQL?

Create a user-defined table type that corresponds to the table that you want to populate. Pass the user-defined table to the stored procedure as a parameter. Inside the stored procedure, select the data from the passed parameter and insert it into the table that you want to populate.

Can we pass table as parameter in stored procedure?

Table-Valued Parameters aka TVPs are commonly used to pass a table as a parameter into stored procedures or functions. They are helpful in a way, we can use a table as an input to these routines and we can get rid of dealing more complex steps to achieve this process.

Can we call table function in stored procedure?

You can call a procedure within a table function as long as the procedure is read only. But your way of calling a procedure is not right.

How do I pass a list as a parameter in a stored procedure?

CREATE FUNCTION dbo. SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>'). query('.


2 Answers

Prepared statements are what you need.

CREATE  PROCEDURE `test1`(IN tab_name VARCHAR(40) ) BEGIN  SET @t1 =CONCAT('SELECT * FROM ',tab_name );  PREPARE stmt3 FROM @t1;  EXECUTE stmt3;  DEALLOCATE PREPARE stmt3; END $$ 
like image 112
a1ex07 Avatar answered Sep 23 '22 06:09

a1ex07


You can do it like this:

 DROP PROCEDURE IF EXISTS `getDataUsingSiteCode`;     DELIMITER $$     CREATE PROCEDURE `getDataUsingSiteCode`(           IN tab_name VARCHAR(40),            IN site_ VARCHAR(255)        )         BEGIN           SET @site_code = site_;           SET @sql_ =CONCAT('SELECT * FROM ',tab_name,' WHERE site=?');           PREPARE statement_ FROM @sql_;           EXECUTE statement_ using @site_code;         END$$     DELIMITER ; 
like image 26
Getachew Mulat Avatar answered Sep 22 '22 06:09

Getachew Mulat