How to use variables in SELECT?

半城伤御伤魂 提交于 2019-12-11 14:05:55

问题


I use IBM® Data Studio V4.1.0.1, DB2 v10.5.

This is my stored procedure.

CREATE PROCEDURE test ()
    DYNAMIC RESULT SETS 1
P1: BEGIN
    DECLARE ageInterval INTEGER;

    SELECT (MAX("age")-min("age"))/5
    INTO ageInterval 
    FROM "Schema1"."adult";   


create view "DiscreteTrain" as 
select 
"age"/ageInterval,
"income"
from "Schema1"."train";

END P1

When I deploy it, data studio says DB2ADMIN.TEST: 15: "AGEINTERVAL" is not valid in the context where it is used. SQLCODE=-206, SQLSTATE=42703, DRIVER=3.67.28

How should I use the variable?


回答1:


You cannot use this variable in a view. According to the documentation:

Global variables can be used in any context where an expression is allowed. Unlike a host variable, a global variable can be used in a CREATE VIEW statement.

So, you have some options. You can switch the variable to a global variable by using create variable. Or, you can do the calculation each time:

create view "DiscreteTrain" as 
    select  "age"/a.ageInterval as MyAge, "income"
    from "Schema1"."train" cross join
         (SELECT (MAX("age")-min("age"))/5 as ageInterval
          FROM "Schema1"."adult"
         ) a;


来源:https://stackoverflow.com/questions/22426278/how-to-use-variables-in-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!