我在准备使用循环根据变量的值创建新列的过程时遇到了麻烦。每当该过程运行时,它都会创建一个名为“cntr”的列,而不是 cntr 的值。代码如下:
BEGIN
Declare cntr INT Default 0;
looper: LOOP
set cntr = cntr + 1;
if cntr = 334 THEN
leave looper;
end if;
alter table hour_time_stamp
add column cntr int;
insert into hour_time_stamp (cntr)
select truncate(time_stamp/3600000000000,0) from `events`
where unit_id=cntr
order by time_stamp DESC;
END loop looper;
END
有人知道如何将变量的值命名为列吗?
最佳答案
您需要执行动态sql。构造一个字符串,其中包含所需的命令加上 cntr 的值,然后对其调用execute。例如:
execute 'alter table hour_time_stamp
add column ' + cntr + ' int';
要插入到列中,您必须类似地构造插入语句。
出于调试目的,将两个 sql 字符串保存到 varchar 变量中并打印出来以确保它们保存 cntr 值可能会有所帮助。
关于mysql - 在 MySQL 中,是否可以将变量的值命名为列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24041005/