MySQL stored procedure passing table name parameter example

I recently developed a project that uses mysql, and some of the processes want to be implemented using stored procedures, but when using stored procedures, I found that parameters such as table names, column names, etc. cannot be directly passed externally, and a pattern of dynamic splicing strings is required to achieve this. , put an example here, which is convenient for future development:
addtable is the in variable passed in from the outside, and here is the table name passed in:

BEGIN #String

variable used to store the sql spliced ​​statement
DECLARE v_sql varchar(1024 ) DEFAULT '0'; 

#Assign a value to a string, use the mysql function CONCAT to synthesize the concatenated string into a string and assign it to a variable.
SET v_sql=CONCAT('select * from ', addtable ,' limit 0,10');  

#PREPARE statement is used to prepare a statement
SET @lastdata = v_sql;
PREPARE lastdata FROM @lastdata;  

#execute function is used to execute the The processed statement
EXECUTE lastdata;

END

can pass the table name, column name, etc. through the above method, and we can write a more powerful stored procedure

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326204362&siteId=291194637