12

I'm trying to write a MySQL function with a select inside, but always get a NULL return

CREATE FUNCTION test (i CHAR)
RETURNS CHAR
NOT DETERMINISTIC
BEGIN
DECLARE select_var CHAR;
SET select_var = (SELECT name FROM table WHERE id = i);
RETURN select_var;
END$$

mysql> SELECT test('1')$$
+-----------------+
|    test('1')    |
+-----------------+
| NULL            | 
+-----------------+
1 row in set, 1 warning (0.00 sec)

mysql> 
mysql> 
mysql> SHOW WARNINGS
    -> $$
+---------+------+----------------------------------------+
| Level   | Code | Message                                |
+---------+------+----------------------------------------+
| Warning | 1265 | Data truncated for column 'i' at row 1 | 
+---------+------+----------------------------------------+
1 row in set (0.00 sec)
6
  • this might be obvious but is there a row in table with id = 1 ? Commented Nov 23, 2011 at 10:22
  • when I run the select on its own, it comes back with a result. Commented Nov 23, 2011 at 10:27
  • don't think that would cause this error. Commented Nov 23, 2011 at 10:33
  • is column "name" of type CHAR? Commented Nov 23, 2011 at 10:43
  • You forgot to tell us what the expected result was, or what the table schema is, or what its contents look like. Commented Nov 23, 2011 at 10:45

5 Answers 5

12

Does it works with this :

CREATE FUNCTION test (i CHAR)
 RETURNS VARCHAR(SIZE)
 NOT DETERMINISTIC
 BEGIN
  DECLARE select_var VARCHAR(SIZE);
  SET select_var = (SELECT name FROM table WHERE id = i);
  RETURN select_var;
 END$$
Sign up to request clarification or add additional context in comments.

Comments

4

try to specify the size of char return type. for example if name can be of 20 characters then try

RETURNS CHAR(20)

1 Comment

Thanks!! Thought that just setting CHAR would be automatic.
1

You have a error in your code, if you need only a result, you obtain it from a simple select an assign with the word INTO like this, remember, it return the last one.

CREATE FUNCTION test (i CHAR)
 RETURNS VARCHAR(SIZE)
 NOT DETERMINISTIC
 BEGIN
  DECLARE select_var VARCHAR(SIZE);
  SELECT name INTO select_var FROM table WHERE id = i;
  RETURN select_var;
 END$$

Comments

1
DELIMITER $$

USE `mydatabase`$$

DROP FUNCTION IF EXISTS `fnGetActiveEventId`$$

CREATE DEFINER=`mydbuser`@`%` FUNCTION `fnGetActiveEventId`() RETURNS INT(11)
BEGIN   
    SET @eventId = (SELECT EventId FROM `Events` WHERE isActive=1 ORDER BY eventId DESC LIMIT 1);   
    
    RETURN @eventId;
    END$$

DELIMITER ;

Comments

0

You have a table named table? Escape that name if that is really what it is:

(SELECT name FROM `table` WHERE id = i);

or put the table name in....it seems to be missing

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.