CREATE PROCEDURE p_create_view()
BEGIN
DECLARE tableName VARCHAR (100)
DECLARE stopFlag INT
DECLARE sql1 VARCHAR (1000)
DECLARE cursor_name CURSOR FOR SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_NAME LIKE 'test_2014%'
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET stopFlag=1
SET @sql1='create view test as select id,name from '
OPEN cursor_name
REPEAT
FETCH cursor_name INTO tableName
SELECT CONCAT(@sql1,tableName,' UNION ALL SELECT id,name FROM ') INTO @sql1 FROM DUAL
UNTIL stopFlag END REPEAT
CLOSE cursor_name
SELECT SUBSTR(@sql1,1,LENGTH(@sql1)-31) INTO @sql1 FROM DUAL
PREPARE step FROM @sql1
EXECUTE step
END
简单的方法是你在存储过程中打印SQL,set y_sql=concat_ws(' ','insert','into',tmp4data,'value','(',var1,var2,')')
select y_sql
看看y_sql合并生什么, 其次在动态SQL过程中, 你定义的tmp4data到底是变量还是表的名称,如果是名称就需要添加分号
mysql存储过程支持用表作为参数。这个问题在MySQL 5.0以前非常麻烦,但是在MySQL 5.0.13版之后,由于引入了PREPARE语句,一切变得简单了。
例子如下(已验证):
DROP PROCEDURE IF EXISTS `newtable`
CREATE PROCEDURE `newtable`(IN tname varchar(64))
BEGIN
SET @sqlcmd = CONCAT('CREATE TABLE ', tname, ' (id int NOT NULL AUTO_INCREMENT, name varchar(64) DEFAULT NULL, PRIMARY KEY (`id`))')
PREPARE stmt FROM @sqlcmd
EXECUTE stmt
DEALLOCATE PREPARE stmt
END
call newtable('abc')
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)