Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a function in DB2 that returns the value of a sequence?

Tags:

function

sql

db2

How to create a function in DB2 that obtains a value from a sequence and returns it?

It should be possible to use that function in select or insert statement, e.g:

select my_func() from xxx
insert into xxx values(my_func())

Basically I am using the sequence value in a complex formula, and I'd like to encapsulate the calculation inside a function.

Edit: I am not asking how to simply get next value from sequence.

like image 268
Juha Syrjälä Avatar asked May 13 '11 13:05

Juha Syrjälä


People also ask

How do you find the current value of a sequence in Db2?

You can access the value of a sequence using the NEXTVAL or CURRVAL operators in SQL statements. You must qualify NEXTVAL or CURRVAL with the name (or synonym) of a sequence object that exists in the same database, using the format sequence. NEXTVAL or sequence. CURRVAL.

How do you create a function in Db2?

If the function cannot be created as an inlined function, Db2 attempts to create a compiled SQL scalar function. For more information on the syntax and rules for these types of functions, see CREATE FUNCTION (inlined SQL scalar) and CREATE FUNCTION (compiled SQL scalar).

How do I run a Db2 function?

To ensure that Db2 executes the external action for each row of the result table, put the user-defined function invocation in the SELECT list. Invoking a nondeterministic user-defined function from a predicate can yield undesirable results. The following example demonstrates this idea.


1 Answers

CREATE FUNCTION "MYSCHEMA"."MY_FUNC"(PARAM1 VARCHAR(4000))
     RETURNS INT
SPECIFIC SQL110520140321900 BEGIN ATOMIC
     DECLARE VAR1 INT;
     DECLARE VAR2 INT;
     SET VAR1  = NEXTVAL FOR MY_SEQ;
     SET VAR2 = VAR1 + 2000; --or whatever magic you want to do
     RETURN VAR2;
END

To try it out:

SELECT MY_FUNC('aa') FROM SYSIBM.SYSDUMMY1;
like image 156
Ville Vuorio Avatar answered Sep 21 '22 00:09

Ville Vuorio