首頁 > 資料庫 > mysql教程 > MySQL – Dynamic SQL with EXECUTE and PREPARE Statements_MySQL

MySQL – Dynamic SQL with EXECUTE and PREPARE Statements_MySQL

WBOY
發布: 2016-06-01 13:08:16
原創
1164 人瀏覽過

MySQL supports Dynamic SQL with the help of EXECUTE and PREPARE statements. Suppose you have a scenario where you need to pass table name as parameter value and returns all column values, you can use Dynamic SQL.

Let us create this table and data.

CREATE TABLE TestTable (ID INT, Col VARCHAR(4));<br> INSERT INTO TestTable (ID, Col)<br> SELECT 1, 'A'<br> UNION ALL<br> SELECT 1, 'B'<br> UNION ALL<br> SELECT 1, 'C'<br> UNION ALL<br> SELECT 2, 'A'<br> UNION ALL<br> SELECT 2, 'B'<br> UNION ALL<br> SELECT 2, 'C'<br> UNION ALL<br> SELECT 2, 'D'<br> UNION ALL<br> SELECT 2, 'E';<br>

Now pass the table name as a parameter and returns all rows from it.

SET @table_name:='TestTable';<br> SET @sql:=CONCAT('SELECT * FROM ',@table_name);<br> PREPARE dynamic_statement FROM @sql;<br> EXECUTE dynamic_statement;<br> DEALLOCATE PREPARE dynamic_statement;

The variable @table_name is assigned name of the table. The variable @sql forms SELECT statement concatenating the Table name so the actual SELECT statement becomes SELECT * FROM TestTable. The PREPARE statement prepares the statement for execution and assigns a name (in this case it is dynamic_statement). EXECUTE command executes the statement prepared by the prepared name dynamic_statement and produces the result. The DEALLOCATE command releases the prepared statement.

So the result is

ID Col 1 A 1 B 1 C 2 A 2 B 2 C 2 D 2 E
登入後複製

Reference: Pinal Dave ( http://blog.sqlauthority.com )

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板