有效查询,失败视图

时间:2018-09-17 01:04:22

标签: sql view db2

我在使用某些DB2 SQL时遇到问题,确实可以使用一些帮助。

简而言之,人们希望我创建一个视图。我编写了一个查询,该查询可以正常工作并返回我们想要的内容……但是当我用“ CREATE VIEW”语句包装它时,当我用任何内容查询该视图时,该视图都会引发错误。

查询为(名称明显更改):

SELECT DISTINCT "QTable"."Add" "Q_Add", "QTable"."Approved" "Q_Approved", "QTable"."Link" "Q_Link"
 FROM (( 
SELECT * FROM db.schema.VTable) 
 "QTable" LEFT OUTER JOIN (SELECT * FROM db.schema.ETable) 
"QStat" on "QTable"."Status" = "QStat"."ETable") 

每次运行此命令,我都会得到10条记录。太棒了,这就是我想要的。当我将其包装为View时,请输入以下内容:

CREATE VIEW TestSchema.TestTable AS
SELECT * FROM ( *query I just wrote above*)

它运行(很快),但是随后我运行了一个基本的SELECT * FROM viewname,我总是遇到以下相同的错误:

SQL0206N  "QTable.Status" is not valid in the context where it is used. SQLSTATE=42703

我已经被卡住了一段时间了。我假设我在创建错误的视图。有任何想法吗?提示?

编辑:DB2 11.1

2 个答案:

答案 0 :(得分:2)

我将除去所有的括号和引号。我怀疑它们不是必需的,除非DB2是非常不标准的sql。我将引号留了下来,尽管除非保留字,否则我也会将所有引号都删除。

没有理由做类似from (select * from table)

的事情

查询应为:

SELECT DISTINCT "QTable"."Add" "Q_Add", "QTable"."Approved" "Q_Approved", "QTable"."Link" "Q_Link"
FROM db.schema.VTable QTable 
LEFT OUTER JOIN  db.schema.ETable "QStat" on "QTable"."Status" = "QStat"."ETable"

您的视图也不应该是create view as select * from (...),而应该是:

create view myView as
SELECT DISTINCT "QTable"."Add" "Q_Add", "QTable"."Approved" "Q_Approved", "QTable"."Link" "Q_Link"
FROM db.schema.VTable QTable 
LEFT OUTER JOIN  db.schema.ETable "QStat" on "QTable"."Status" = "QStat"."ETable"

答案 1 :(得分:1)

您可能有其他问题。我只是在DB2 10.5中尝试过,并且效果很好:

create table vtable (
  "Add" int,
  "Approved" int,
  "Link" varchar(20),
  "Status" int
);

create table etable (
  "ETable" int
);

create view my_view1 as
select
  *
from
  (
    SELECT
      DISTINCT "QTable"."Add" "Q_Add",
      "QTable"."Approved" "Q_Approved",
      "QTable"."Link" "Q_Link"
    FROM
      (
          ( SELECT * FROM VTable) "QTable"
          LEFT OUTER JOIN
          (
            SELECT
              *
            FROM ETable
          )
          "QStat" on "QTable"."Status" = "QStat"."ETable"
      )
  )

无论如何,您的括号过多。删除不需要的内容。

QTable必须始终用双引号引起来,例如"QTable"