简体   繁体   English

在DB2 / AS400上使用Views和CTE

[英]Using Views and CTE on DB2/AS400

a Generic question.. 一个通用的问题

I have an employee Table( EMPMAST ) which has the New as well old Employee data. 我有一个雇员表( EMPMAST ),其中包含新的以及旧的Employee数据。 There is a flag called Current? 有一个标记为Current? which is 'Y' if he/she is a current employee. 如果他/她是当前雇员,则为“ Y”。 Now I have to select records in my SQLRPGLE with only the current records and also some other criteria's(For Example EMPNAME = 'SAM') .What is the best way to deal with it. 现在,我必须在SQLRPGLE中选择仅包含当前记录以及其他一些条件的记录(例如EMPNAME ='SAM')。处理它的最佳方法是什么。 (in terms of performance and system usage) (根据性能和系统使用情况)

  1. To create a View over the EMPMAST with Current? 要使用“ Current?EMPMAST上创建视图Current? = 'Y'. ='Y'。 Then use it in the program with other conditions. 然后在其他条件下在程序中使用它。
  2. Use a CTE(With AS) in the Program which would have the Condition Current = 'Y' and use it. 其中将具备条件的程序中使用CTE(带AS) Current =“Y”,并使用它。
  3. use the table directly without CTE and View 不使用CTE和View即可直接使用表格
  4. any other option 任何其他选择

Options 1, 2 and 3 would all perform the same. 选项1、2和3都将执行相同的操作。 They would likely all have the same optimized query and access plan. 它们可能都具有相同的优化查询和访问计划。

A CTE vs. a View are two different things. CTEView是两件事。 A View would be appropriate for a query that is going to be used in multiple locations, A CTE is only available in the query in which it is defined. View将适用于要在多个位置使用的查询, CTE仅在定义它的查询中可用。 I usually don't use the CTE except to replace a complex subquery. 我通常不使用CTE除非要替换复杂的子查询。 In your case the condition is simple enough to be contained in the where clause so I don't see the need to introduce additional complexity. 在您的情况下,条件足够简单,可以包含在where子句中,因此我认为无需引入其他复杂性。

Some folks will tell you not to query the table directly in the program, but to always use a view. 有些人会告诉您不要在程序中直接查询表,而要始终使用视图。 That way you add an extra layer of insulation between the program and the database, and you can still define record structures with ExtName , and not have to worry about changes to the table unless they affect the view itself. 这样,您就可以在程序和数据库之间添加额外的隔离层,并且仍然可以使用ExtName定义记录结构,而不必担心对表的更改,除非它们影响视图本身。 In this case you would likely have a dedicated view for each program that uses the table. 在这种情况下,您可能会对使用该表的每个程序都有一个专用的视图。

I tend to just use a hybrid of these techniques. 我倾向于只使用这些技术的混合体。 I query tables, CTE's, or Views depending on the situation, and define my record structures explicitly in the program. 我根据情况查询表,CTE或视图,并在程序中显式定义我的记录结构。 I prefer to just query the table, but if I have some complex query logic which is unique to the program, I will use a CTE. 我更喜欢只查询表,但是如果我有一些程序独有的复杂查询逻辑,我将使用CTE。 I do have a few Views, but these are limited to those queries that happen in multiple programs where I want to ensure the same logic is applied consistently. 我确实有一些视图,但是这些视图仅限于在多个程序中发生的查询,在这些程序中,我想确保一致地应用相同的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM