我试图基于IF条件在UDF中返回两个不同的SQL语句。到目前为止我还没能正确完成,下面的代码不起作用。我怎么能这样做?
CREATE FUNCTION BELSIZE.TEST (aSTRING VARCHAR(50))
RETURNS TABLE(
column1 INTEGER
, column2 INTEGER
, column3 VARCHAR(50)
)
------------------------------------------------------------------------
F1: BEGIN ATOMIC
DECLARE v_string VARCHAR(50);
SET v_string = aSTRING;
IF v_string = '123' THEN
With v (column1, column2, column3) as (
VALUES (1, 10231011, 'PRINCIPAL')
, (1, 10231012, 'ADDITIONAL')
, (-1, 10231031, 'REDEEM')
) select * from v;
END IF;
RETURN
With v (column1, column2, column3) as (
VALUES (1, 10231011, 'PRINCIPAL 456')
, (1, 10231012, 'ADDITIONAL 456')
, (-1, 10231031, 'REDEEM 456')
) select * from v;
END
感谢。
答案 0 :(得分:0)
由于您需要基于输入字符串的2个不同结果,因此您的return语句应该位于IF-ELSE
逻辑上。您处理它的方式在查询中是错误的。它总是试图在返回块中返回一个。
我已更正符合您要求的查询。使用IF-ELSE
逻辑。它是用SQL-SERVER
CREATE FUNCTION dbo.testFn(@aSTRING VARCHAR(50))
RETURNS @rtnTable TABLE(
column1 INTEGER
, column2 INTEGER
, column3 VARCHAR(50)
)
AS
BEGIN
IF @aSTRING = '123'
BEGIN
INSERT INTO @rtnTable
VALUES (1, 10231011, 'PRINCIPAL')
, (1, 10231012, 'ADDITIONAL')
, (-1, 10231031, 'REDEEM')
END
ELSE
BEGIN
INSERT INTO @rtnTable
VALUES (1, 10231011, 'PRINCIPAL 456')
, (1, 10231012, 'ADDITIONAL 456')
, (-1, 10231031, 'REDEEM 456')
END
RETURN
END
答案 1 :(得分:0)
您应该指定您的平台和Db2版本......
但是,我不相信这会有所作为。
Db2从用户定义表函数(UDTF)或存储过程返回行的方式是以函数/过程内部定义的游标结束。
所以你需要这样的东西......
CREATE FUNCTION BELSIZE.TEST (aSTRING VARCHAR(50))
RETURNS TABLE(
column1 INTEGER
, column2 INTEGER
, column3 VARCHAR(50)
)
begin atomic
declare C1 cursor with return to client for
With v (column1, column2, column3) as (
VALUES (1, 10231011, 'PRINCIPAL')
, (1, 10231012, 'ADDITIONAL')
, (-1, 10231031, 'REDEEM')
) select * from v;
declare C2 cursor with return to client for
With v (column1, column2, column3) as (
VALUES (1, 10231011, 'PRINCIPAL 456')
, (1, 10231012, 'ADDITIONAL 456')
, (-1, 10231031, 'REDEEM 456')
) select * from v;
IF v_string = '123' THEN
open C1;
else
open C2;
END IF;
RETURN
END
答案 2 :(得分:0)
我会将你的UDF编码为这样的
CREATE FUNCTION BELSIZE.TEST (aSTRING VARCHAR(50))
RETURNS TABLE(
column1 INTEGER
, column2 INTEGER
, column3 VARCHAR(50)
)
RETURN
SELECT column1, column2, column3 FROM TABLE(
VALUES (0, 1, 10231011, 'PRINCIPAL')
, (0, 1, 10231012, 'ADDITIONAL')
, (0,-1, 10231031, 'REDEEM')
, (1, 1, 10231011, 'PRINCIPAL 456')
, (1, 1, 10231012, 'ADDITIONAL 456')
, (1,-1, 10231031, 'REDEEM 456')
) AS v(i, column1, column2, column3)
WHERE i = CASE WHEN aSTRING = '123' THEN 0 ELSE 1 END