Question

This function:

CREATE FUNCTION `GetCardID`(numId INT) RETURNS int(11)
    DETERMINISTIC
BEGIN
    DECLARE retcard INT(11);
    SELECT id
    INTO retcard
    FROM cards
    WHERE `number` = numId
        AND enabled = 1
    LIMIT 1;
    RETURN retcard;
END

Always returns null even when the query:

SELECT id FROM cards WHERE `number`=<Insert Value Here> AND ENABLED = 1 LIMIT 1;

returns a valid value for the same value used in and the function parameter.

For instance:
SELECT id FROM cards WHERE number=12345 AND ENABLED = 1 LIMIT 1;
-- returns an id, while
GetCardId(12345);
-- returns null

Any ideas what I'm missing here? I consider myself quite skilled at SQL, but a little green on SP's.

Était-ce utile?

La solution

How big is the data that you are taking into your function? Is it possible that the number is larger than what will fit into an INT?

Autres conseils

Christopher here is your function. Try this and it should work:

CREATE FUNCTION [dbo].[GetCardID]
(  
    @Num_ID INT

)  
RETURNS int  
AS  
BEGIN  
    declare @retcard int    

    select Top 1 @retcard = id 
    FROM cards 
    where number = @num_Id
    AND enabled = 1

    return @retcard



END

Always returns NULL:

Get rid of DETERMINISTIC clause in Procedure definition. MySQL caches the responses from such procedure or functions.

Excerpt from MySQL:

A routine is considered “deterministic” if it always produces the same result for the same input parameters, and “not deterministic” otherwise. If neither DETERMINISTIC nor NOT DETERMINISTIC is given in the routine definition, the default is NOT DETERMINISTIC. To declare that a function is deterministic, you must specify DETERMINISTIC explicitly

MySQL 5.5 - Creating Procedure or Function

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top