函数 存储过程动态sql
delimiter $$
drop procedure if exists ap_dynamicSQL $$
测试动态sql
CREATE PROCEDURE test_dynamicSQL(as_sql varchar(4000)) begin #declare ls_sql varchar(4000) ; #set ls_sql=‘select 1 as a , 2 as b , 3 as c ;select version();‘ ; #把所有数据拼接到这个sql中 set @sql = as_sql ; prepare stmt from @sql ; execute stmt ; deallocate prepare stmt; END$$ call test_dynamicSQL(‘select version();‘)$$
测试函数
delimiter $$ CREATE FUNCTION `testf`(usrid BIGINT) RETURNS int BEGIN DECLARE weekEnds int; select count(1) from userstest where id=usrid into weekEnds; RETURN weekEnds; END; $$ delimiter ;
测试过程
delimiter $$ CREATE PROCEDURE `test_pro`(as_tablename varchar(40), as_tableschema varchar(40)) SQL SECURITY INVOKER BEGIN DECLARE fetchOK int default 1; DECLARE ls_colname varchar(40); DECLARE ls_return varchar(1000) default ‘‘; DECLARE cur_code cursor for select column_name from information_schema.columns where table_name=as_tablename and table_schema=as_tableschema; DECLARE continue handler for not found BEGIN set fetchOK=0; commit; END; open cur_code; allcodes:loop fetch cur_code into ls_colname; if fetchOK then set ls_return=concat(ls_return, ‘new.‘, ls_colname, ‘,‘); else leave allcodes; end if; end loop allcodes; close cur_code; set ls_return=concat(‘insert into ‘, as_tableschema, ‘,‘, as_tablename, ‘ values(‘, substr(ls_return,1,length(ls_return)-1), ‘)‘); select ls_return as sqlcmd; END; $$ delimiter ;
call test_pro(‘userstest‘, ‘testdb‘);
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。