Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

db2 - Execute SQL queries within views conditionally

We had a couple of huge SQL statements (executed within an embedded sqlrpgle program) for which we created separate views - one for each SQL.

The SQL statements were being executed within the programs conditionally. That is, the program had some conditional logic in it (written in RPG) which would determine whether we would execute one query or the other.

Now what we are trying to do is to create a single view which would be an equivalent of the RPG program.

That is somehow include the conditional logic in the view code.

Below is the simplest pseudocode of the view that I could imagine of what I am trying to achieve

if (condition 1 is true)
   Select * from table1;
else
   Select * from table2;

The if condition logic needs to be part of the view that I am trying to create. Is something like this possible in DB2?

Please note that the condition 1 used above is a very high level representation. The logic is actually comprised of several program calls etc.

Any advise would be appreciated.

question from:https://stackoverflow.com/questions/65940677/execute-sql-queries-within-views-conditionally

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the two parts return the same number of columns, and they are of compatible types, then you could just code the view like this.

CREATE VIEW V AS
WITH C(C) AS ( VALUES (condition) )
SELECT * FROM table1, C WHERE C = 1 
UNION ALL
SELECT * FROM table2, C WHERE C = 0

or maybe consider using a table function


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...