mysql执行动态sql语句

 今天oracle群上有人问mysql可不可以执行动态的sql语句,搜了一下,居然可以。

SET @tsql='select * from companyinfo';
 PREPARE stmt1 FROM @tsql;
 EXECUTE stmt1;

 

 

 

SET @fid='fid';
SET @table1='companyinfo';
 SET @tsql=CONCAT('select ',@fid,' from ',@table1);
 PREPARE stmt1 FROM @tsql;
 EXECUTE stmt1;

 

 

mysql> use test
Database changed
mysql> SET @fid='fid';
Query OK, 0 rows affected (0.00 sec)

mysql> SET @table1='companyinfo';
Query OK, 0 rows affected (0.00 sec)

mysql>  SET @tsql=CONCAT('select ',@fid,' from ',@table1);
Query OK, 0 rows affected (0.00 sec)

mysql>  PREPARE stmt1 FROM @tsql;
Query OK, 0 rows affected (0.00 sec)
Statement prepared

mysql>  EXECUTE stmt1;
+------+
| fid  |
+------+
| 1001 |
+------+
1 row in set (0.00 sec)

 

 

 

mysql> use test
Database changed
mysql> SET @tsql='select Titleof into @ename from employeelist where eid=2';
Query OK, 0 rows affected (0.00 sec)

mysql>  PREPARE stmt1 FROM @tsql;
Query OK, 0 rows affected (0.00 sec)
Statement prepared

mysql>  EXECUTE stmt1;
Query OK, 1 row affected (0.00 sec)

mysql>  SELECT @ename;
+-----------+
| @ename    |
+-----------+
| 杩炶姵鑺?   |
+-----------+
1 row in set (0.00 sec)

mysql>

 

你可能感兴趣的:(以前的文章)