2015-10-16 66 views
0

我想做一個過程,如果它不存在,將在給定的表中創建一列。新列的名稱應該來自我稱爲「colname」的參數。如何訪問MySQL過程參數?

但是這不起作用,它創建列,但與實際名稱「colname」,而不是我調用它的值。我在這裏做錯了什麼?

delimiter ;; 
create procedure autoColumns (colname varchar(64)) 
begin 
    declare continue handler for 1060 begin end; 
    alter table affiliates add colname DECIMAL(5,2); 
end;; 
call autoColumns('testColumn');; 

回答

1

你很接近,OP。

create table affiliates (id int); 

delimiter // 
create procedure autoColumns(colname varchar(64)) 
begin 
    set @dml = concat('alter table affiliates add column ', colname, ' decimal(5,2)'); 
    prepare stmt from @dml; 
    execute stmt; 
end 
// 
delimiter ; 

call autoColumns('test2'); 

select * from affiliates; -- you'll see ID and test2 columns 

這應該爲你做。也看到這個問題:How To have Dynamic SQL in MySQL Stored Procedure

+0

這是完美的,非常感謝! :) –

1

在mysql變量不能用於dinamically確定表或列的名稱,只有值。爲了實現你想要的東西,你需要將sql組裝成字符串,然後使用prepared statement以非常方式執行它。請參閱鏈接文檔中的第三個示例。