SQL 如何在 DB2 中创建一个返回序列值的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5992308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 10:32:09  来源:igfitidea点击:

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

sqlfunctiondb2

提问by Juha Syrj?l?

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

如何在 DB2 中创建一个从序列中获取值并返回它的函数?

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

应该可以在 select 或 insert 语句中使用该函数,例如:

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.

编辑:我不是在问如何简单地从序列中获取下一个值。

回答by Ville Vuorio

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;