2012-10-17 29 views
1

我写了一个小的函数返回值:从MySQL功能

CREATE TABLE states 
    (`id` int, `name` varchar(2)) 
; 

INSERT INTO states 
    (`id`, `name`) 
VALUES 
    (1, 'md'), 
    (2, 'tx'), 
    (3, 'ma') 
; 

delimiter // 

create function states_repeated (s varchar(2)) 
returns int 
begin 
    insert into sid select count(*) from states where states.name=s ; 
    return sid ; 
end// 

delimiter ; 

select states_repated('ma') ; 

但这返回

ERROR 1146 (42S02): Table 'test.sid' doesn't exist 

如何返回该值?

+0

变化INSERT在'插入计数( *)从state.state = s;'的状态转换为sid – SYNCRo

回答

2

尝试这样的事情,

DECLARE _returnValue INT; 
SET _returnValue = (select count(*) from states where states.state = s); 
return _returnValue; 

的完整代码

delimiter // 

create function states_repeated (s varchar(2)) 
returns int 
begin 
    DECLARE _returnValue INT; 
    SET _returnValue = (select count(*) from states where states.name = s); 
    return _returnValue; 
end// 

delimiter ; 
0

我认为MySQL的函数和存储过程只是SELECT返回声明的变量