Dynamic column name in function

  • Follow


Hello,

I want to use a cursor in a function which has a select with a dynamic 
column name and returns the value of this relevant column depending on 
the input parameter of the function.

I wrote it like this:

----------------

CREATE FUNCTION `testdb`.`dyncoltest` (my_column_name varchar(255)) 
RETURNS INT(11)

BEGIN

DECLARE RETURN_VALUE INT default 0;

DECLARE DYNAMIC_SELECT CURSOR for
     select my_column_name
     from MY_TABLE
     limit 1;


open DYNAMIC_SELECT;
FETCH DYNAMIC_SELECT INTO RETURN_VALUE;
close DYNAMIC_SELECT;

RETURN RETURN_VALUE;

END $$

---------------------

If I call this function with "select dyncoltest('age')" it doesn't 
return the value of the 'age' column, but the string value 'age' itself.

So the cursor is interpreted like this:

select 'age' from MY_TABLE

instead of

select age from MY_TABLE


How can I achieve that the input parameter is used as column name and 
not as string value?

Thx
JEns
0
Reply Jens 9/29/2010 7:48:10 PM

Il 29/09/2010 21.48, Jens Riedel ha scritto:
> Hello,
> 
> I want to use a cursor in a function which has a select with a dynamic
> column name and returns the value of this relevant column depending on
> the input parameter of the function.

You could try the prepared statements

http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html

Actually I'm not sure that mysql allows you to write prepared statements
inside a function / procedure...

M.
0
Reply Mau 9/30/2010 7:06:32 AM


1 Replies
612 Views

(page loaded in 0.042 seconds)

Similiar Articles:













7/22/2012 10:17:59 AM


Reply: