2012-10-17 80 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返回聲明的變量