2012-02-07 82 views
3

我有一个存储过程,它将字符串分开并以select结尾。带INSERT的MySQL INSERT

我想在存储过程运行的插件像你这样在选择

像这样的事情

INSERT INTO .... 
CALL sp_split... 

我的分裂做插入看起来是这样的:

DELIMITER $$ 

CREATE DEFINER=`root`@`localhost` PROCEDURE `split_with_id`(id INT, input varchar(1000), delim VARCHAR(10)) 
BEGIN 
    declare foundPos tinyint unsigned; 
    declare tmpTxt varchar(1000); 
    declare delimLen tinyint unsigned; 
    declare element varchar(1000); 

drop temporary table if exists tmpValues; 
create temporary table tmpValues 
( 
    `id` int not null default 0, 
    `values` varchar(1000) not null default '' 
) engine = memory; 

set delimLen = length(delim); 
set tmpTxt = input; 

set foundPos = instr(tmpTxt,delim); 

while foundPos <> 0 do 
    set element = substring(tmpTxt, 1, foundPos-1); 
    set tmpTxt = replace(tmpTxt, concat(element,delim), ''); 


    insert into tmpValues (`id`, `values`) values (id, element); 

    set foundPos = instr(tmpTxt,delim); 
end while; 

if tmpTxt <> '' then 
    insert into tmpValues (`id`, `values`) values (id, tmpTxt); 
end if; 

select * from tmpValues; 

END

+1

我相信这个问题可能是你想要实现http://stackoverflow.com/questions/653714/how-to-select-into-temp-table-from-stored-procedure – Robb 2012-02-07 16:06:51

+0

这是一个格栅文章对于MS SQL,但不幸的是,MySQL不支持exec – esack 2012-02-07 20:37:58

回答

1

创建包装函数并让它调用过程。然后SELECT它通常。

DELIMITER $$ 

CREATE FUNCTION `f_wrapper_split` (strin VARCHAR(255)) 
RETURNS VARCHAR(255) 
BEGIN 
    DECLARE r VARCHAR(255); 
    CALL sp_split(strin); 
    RETURN r; 
END 
$$ 

当然,如果sp_split返回多个结果,你需要的功能适应,也许,采取INT输入以及并返回特定的结果。然后多次调用它。

这不是很漂亮,但这是我能想到的最好的。

+0

我的分割返回了一个表 – esack 2012-02-07 22:09:28

+0

是否有可能将“sp_split”的DDL包含到问题中? – Naltharial 2012-02-07 22:15:14

+0

我的分割返回一个表格:AccountID | PermissionID我需要找到一种方法来执行以下代码:INSERT INTO tablename(AccountID,PermissionID)SELECT AccountID,PermissionID FROM tempTble“但带有”CALL“类似于”INSERT INTO tablename(AccountID,PermissionID)CALL sp_split()“ – esack 2012-02-07 22:16:08