Mysql
這個 MySQL 5.6 過程定義有什麼問題?使用變數作為表名
只是不明白為什麼會拋出這個錯誤?
錯誤程式碼:1064。您的 SQL 語法有錯誤;檢查與您的 MySQL 伺服器版本相對應的手冊,以在第 1 行的“NULL”附近使用正確的語法
drop procedure if exists dividir_tabla_por_usuario; delimiter // create procedure dividir_tabla_por_usuario(tabla varchar(100), columna_usuario varchar(100), columna_fecha varchar(100)) begin set @i = 0; set @q1 = concat('select count(*) from (select distinct ', columna_usuario ,' from ', tabla , ' order by ', columna_usuario ,' asc) as t1 into @c'); prepare p1 from @q; execute p1; while @i <= @c do set @r = 0; set @q2 = concat('select * from ', tabla , ' where ', columna_usuario ,' = (select ', columna_usuario ,' from (select @r:=@r +1 as ord, ', columna_usuario ,' from (select distinct ', columna_usuario ,' from ', tabla , 'order by ', columna_usuario ,' asc) as t2) as t3 where ord = ', @i ,' ) order by ', columna_fecha ,' asc limit 30000'); prepare p2 from @q2; execute p2; set @i := @i + 1; end while; end// delimiter ; call dividir_tabla_por_usuario('mytable', 'mycolumn_1', 'mycolumn_2');
錯別字,總是錯別字。
這是最終的工作程式碼:
drop procedure if exists dividir_tabla_por_usuario; delimiter // create procedure dividir_tabla_por_usuario(tabla varchar(100), columna_usuario varchar(100), columna_fecha varchar(100)) begin set @i = 0; set @q1 = concat('select count(*) from (select distinct ', columna_usuario ,' from ', tabla , ' order by ', columna_usuario ,' asc) as t1 into @c'); prepare p1 from @q1; execute p1; while @i <= @c do set @r = 0; set @q2 = concat('(select distinct ', columna_usuario ,' from ', tabla , ' order by ', columna_usuario ,' asc) as t2)'); set @q3 = concat('(select @r:=@r +1 as ord, ', columna_usuario ,' from ',@q2, ' as t3 where ord = ', @i ,' )'); set @q4 = concat('(select ', columna_usuario ,' from ', @q3); set @q5 = concat('select * from ', tabla , ' where ', columna_usuario ,' = ', @q4 ,' order by ', columna_fecha ,' asc limit 30000'); prepare p2 from @q5; execute p2; set @i := @i + 1; end while; end// delimiter ; call dividir_tabla_por_usuario('mytable', 'mycolumn1', 'mycolumn2');