CREATE VIEW

適用於:已勾選為 Databricks SQL 勾選為 Databricks 執行時

建構虛擬數據表,此虛擬數據表沒有根據 SQL 查詢的結果集或以 yaml 規格為基礎的計量檢視。 ALTER VIEW 而且 DROP VIEW 只更改元資料。

若要執行此語句,您必須是中繼存放區系統管理員,或具有 USE CATALOG 目錄和架構的許可權、USE SCHEMA 目錄和架構的許可權,以及 CREATE TABLE 目標架構中的許可權。

執行此命令的使用者將會成為檢視的擁有者。

Warning

CHAR 長度 VARCHAR 語意(包括 CHAR(n) 空格填充)僅在表格邊界處適用。 視野僅保留一條未改變的柱子;欄位上的任何表達式,如 CAST、 、 函數、別名或新增註解,皆會回傳純 STRING。 由於 CHAR 數值有空格填充,比較方式可能與基底表不同。 例如,一個CHAR(10)值儲存為 'COLLEGE',因此'COLLEGE '會返回column = 'COLLEGE'在表格上,但true會透過false視圖返回。

語法

-- Query-backed or metric view
CREATE [ OR REPLACE ] [ [ GLOBAL ] TEMPORARY ] VIEW [ IF NOT EXISTS ] view_name
    [ column_list ]
    [ with_clause |
      COMMENT view_comment |
      DEFAULT COLLATION collation_name |
      TBLPROPERTIES clause |
      { COPY | NOCOPY } * |
      LANGUAGE YAML ] [...]
    AS { query | $$ yaml_string $$ }

-- Temporary view backed by a data source
CREATE [ OR REPLACE ] [ GLOBAL ] TEMPORARY VIEW [ IF NOT EXISTS ] view_name
    [ column_list ]
    USING data_source [ OPTIONS ( option_key [ = ] option_value [, ...] ) ]

with_clause
   WITH { { schema_binding | METRICS } |
          ( { schema_binding | METRICS } [, ...] } )

schema_binding
   WITH SCHEMA { BINDING | COMPENSATION | [ TYPE ] EVOLUTION }

column_list
   ( { column_alias [ COMMENT column_comment ] } [, ...] )

參數

  • 或替換

    如果已有相同名稱的檢視存在,則會加以取代。 你必須是擁有者,或是有 MANAGE 在視圖上才能更換。 替換視圖的使用者將成為新的擁有者。

    對於 Unity 目錄管理的檢視,使用 COPY * or NOCOPY * 子句來控制替換是否保留現有檢視的元資料,例如授權、註解和標籤。

    對於任何其他觀點,替換它不會保留原始觀點或 table_id所賦予的特權,等同於 DROP VIEW IF EXISTS view_name 接著 CREATE VIEW view_name。 用 ALTER VIEW 來在原地更改視圖而不失去權限。

  • 臨時

    TEMPORARY 檢視僅對建立它們的會話可見,且會在會話結束時被刪除。 在結構中會建立 system.session 一個暫時視圖。

  • 全球臨時

    適用於:勾選為是 Databricks 執行環境

    GLOBAL TEMPORARY 檢視與系統保留的暫存結構 system.global_temp綁定。 你也可以把名稱限定為 global_temp。

  • 若不存在

    只有在檢視不存在時,才會建立檢視。 CREATE VIEW 語句將被忽略,如果同名的視圖已經存在。

    您最多可以指定 IF NOT EXISTS 或 OR REPLACE 中的一個。

  • view_name

    新建立的檢視的名稱。

    若名稱未加限定,則在目前架構中建立持久視圖。

    • 持久視圖:在 Databricks SQL 及 Databricks Runtime 19 及以上版本中, PATH 不會用來選擇目標結構。
    • 暫存檢視:在 Databricks SQL 與 Databricks Runtime 18.0 及以上版本中,您只能以 system.session 或 session來限定名稱。 你只能用或 global_temp來限定全域暫時視圖system.global_temp。 在早期版本中,暫時視圖的名稱必須不加限定。

    完整檢視名稱必須唯一。

    在 hive_metastore 中建立的檢視名稱只能包含英文字母、數字和下劃線(INVALID_SCHEMA_OR_RELATION_NAME)。

  • 指標

    適用於:勾選是 Databricks SQL 勾選是 Databricks 執行環境 16.4 及以上版本 勾 選是 僅 Unity 目錄

    將檢視識別為計量檢視。 檢視必須以 LANGUAGE YAML 定義,而且檢視主體必須是有效的 yaml 規格。

    在 Databricks Runtime 17.2 之前,暫時檢視不支援此子句。

    計量檢視不支援 DEFAULT COLLATION 和 schema_binding 子句。

    度量視圖的 YAML 規範定義 dimensions了 、 measures,且可選 parameters性。 dimensions是檢視的數據行,叫用者可以匯總量值,而 measures 定義檢視的匯總。

    計量檢視的叫用者會使用 量值 表達式來存取已定義的量值,而不是指定聚合函數。

    Important

    這項功能目前處於 公開預覽版。

    可選擇性地,YAML 規範定義 parameters了 :命名值,檢用者在查詢時綁定這些值。 每個參數都有名稱、資料型態,以及一個可選的預設值。 在 和 expression 中dimensionsmeasures以名稱參考參數,然後在查詢視圖時以 table-value 函式傳遞命名參數。 參數需要 Databricks Runtime 18.2 及以上版本。 關於 YAML 語法,請參見 參數。

  • schema_binding

    適用於:勾選為是 Databricks 執行環境 15.3 以上版本

    選擇性地指定檢視如何因基礎物件定義中的變更而適應查詢架構的變更。

    暫存檢視、計量檢視或具體化檢視不支持這個子句。

    • SCHEMA 綁定

      如果查詢資料列清單變更,但下列條件除外,檢視會變成無效:

      • 欄位清單包含星號子句,此外還有其他欄位。 會忽略這些額外的欄。
      • 一或多個數據行的類型會以允許它們使用隱含轉換規則安全地轉換成原始數據行類型的方式變更。
    • SCHEMA 報酬

      如果查詢資料列清單變更,但下列條件除外,檢視會變成無效:

      • 欄位清單包含星號子句,此外還有其他欄位。 會忽略這些額外的欄。
      • 一個或多個數據行的類型會以允許它們使用明確的 ANSI 轉換規則轉換成原始數據行類型的方式變更。

      此為預設行為。

    • SCHEMA 類型演化

      當 SQL 編譯器偵測到對檢視檢視的變更時,檢視會將查詢欄位列表中的任何類型變更納入自己的定義中。

    • SCHEMA 演變

      • 此模式的行為類似 SCHEMA TYPE EVOLUTION,且若視圖未包含明確的 column_list,則會採用欄位名稱、欄位註解或新增或刪除欄位的變更。
      • 只有當查詢無法再解析,或可選檢視 column_list 不再符合選取清單中的 query 表達式數量時,該檢視才會變得無效。

    Note

    Unity 目錄檢視 SCHEMA TYPE EVOLUTION 在或 SCHEMA EVOLUTION 模式中可能儲存的結構結構不再與其查詢的輸出相符。 當查詢此類檢視時,Azure Databricks 會以查詢使用者身份更新儲存的結構。 如果更新失敗,查詢會傳回 FAILED_UPDATE_VIEW_SCHEMA 錯誤。 Unity 目錄僅接受來自檢視擁有者或強制權限的運算更新。 因此,來自未擁有該檢視的使用者的查詢可能會在 專用運算 中失敗,直到儲存的結構更新為止。

    如果目錄以唯讀方式綁定到工作區,該工作區中的專用運算無法更新儲存的結構,即使是檢視擁有者也無法。 在此情況下,請從強制權限的運算中查詢檢視,或從具有目錄讀寫權限的工作區執行以下擁有者步驟。

    為避免此失敗,請執行下列其中一項操作:

    • 查詢從計算中強制執行權限的檢視:無伺服器運算、 標準存取模式 運算,或 SQL 倉儲。 標準存取模式運算需要 Databricks Runtime 17.1.1 或以上版本。
    • 讓檢視擁有者在底層結構變更後查詢檢視。 擁有者的查詢會更新已儲存的結構。
    • 將檢視的所有權轉移至 ...ALTER VIEWOWNER TO 至查詢主體所屬的群組。 檢視擁有者或擁有 MANAGE 權限的使用者只能將所有權轉移給他們同樣所屬的群組。 只有 Metastore 管理員才能將所有權轉移給任何其他主體,例如查詢的使用者。 檢視上的查詢會使用擁有者的權限,因此新擁有者必須對檢視的底層物件擁有所需的權限。
    • 讓檢視擁有者將檢視變更為SCHEMA BINDING或 SCHEMA COMPENSATION 。ALTER VIEW 此時檢視會停止採用結構變更。 若變更與新模式不相容,該變更即失效。
  • column_list

    選擇性地在檢視的查詢結果中標記數據行。 如果您提供一個欄位清單,欄位別名的數目必須與查詢中的表達式數目一致,或在度量檢視的情況下,必須符合 YAML 規格。 如果未指定欄位清單,別名將從檢視的主體中衍生。

    • column_alias

      欄位別名必須是唯一的。

    • column_comment

      描述欄位別名的可選擇的 STRING 常值。

  • view_comment

    提供檢視層級註解的可選 STRING 常數。

  • 預設排序 規則collation_name

    適用於:勾選為是 Databricks SQL 勾選為是 Databricks 執行環境 16.3 及以上版本

    定義在 query內使用的預設排序規則。 如果未指定,預設的排序規則會衍生自建立檢視定義的模式。

    度量檢視不支持此子句。

  • TBLPROPERTIES

    選擇性地設定一個或多個使用者定義的屬性。

  • 複製 * 或 NOCOPY *

    適用於:勾選是 Databricks SQL 勾選是 Databricks 執行環境 18.3 及以上版本 勾 選是 僅 Unity 目錄

    控制將現有檢視 OR REPLACE 取代是否能保留該檢視的元資料,例如授權、註解和標籤。

    • COPY * 保留現有檢視的中繼資料。
    • NOCOPY * 會刪除現有檢視的中繼資料。 取代後只保留新定義中的元資料。

    僅支援形式 * :該子句適用於所有可保留的元資料類別,而非子集。 此條款僅支援 Unity 目錄管理的檢視,且僅限於 OR REPLACE。 在任何其他視圖上使用它都會產生錯誤。

    若省略此子句,預設值依執行時間而定:

    • 在 Databricks Runtime 18.3 中,現有視圖的元資料不會被保留,與 NOCOPY *。 指定 COPY * 保存它。
    • 在 Databricks Runtime 19 及以上版本中,現有檢視的元資料預設會被保留,與 COPY *。 指定 NOCOPY * 要放棄它。
  • AS 查詢

    從基表或其他視圖建構檢視的查詢。

    在 Databricks SQL 及 Databricks Runtime 19 及以上版本中,持久視圖會在建立時擷取會話 路徑 ,並根據該路徑解析此查詢中的未限定名稱,而非呼叫者的會話路徑。 current_path() 而 current_schema() 在查詢中,仍會傳回呼叫者的會話值。 請參見 捕獲路徑。

    度量檢視不支持此子句。

  • AS $$ yaml_string $$

    定義計量檢視的 yaml 規格。

  • 使用 data_source

    它直接用資料來源來支持視圖,而不是查詢,所以你可以在不先定義資料表的情況下查詢檔案。 此子句僅TEMPORARY支援 和 GLOBAL TEMPORARY 視圖,且無法與 合併。AS

    data_source必須是檔案格式,例如 CSV、 AVROORCJSONPARQUET或 。TEXT 有關支援的完整檔案格式清單,請參見 CREATE TABLE [USING]。

  • 選項

    將一個或多個資料來源選項設為鍵值對,例如檔案 path,是否該檔案有 header,以及解析器 mode。 關於每種格式支援的選項,請參閱對應格式參考,例如 讀寫 CSV 檔案。

範例

-- Create or replace view for `experienced_employee` with comments.
> CREATE OR REPLACE VIEW experienced_employee
    (id COMMENT 'Unique identification number', Name)
    COMMENT 'View for experienced employees'
    AS SELECT id, name
         FROM all_employee
        WHERE working_years > 5;

-- Replace a Unity Catalog view while preserving its grants, comments, and tags.
> CREATE OR REPLACE VIEW experienced_employee COPY *
    AS SELECT id, name, department
         FROM all_employee
        WHERE working_years > 5;

-- Replace the same view but drop its existing metadata, keeping only the new definition.
> CREATE OR REPLACE VIEW experienced_employee NOCOPY *
    AS SELECT id, name
         FROM all_employee
        WHERE working_years > 5;

-- Create a temporary view `subscribed_movies`.
> CREATE TEMPORARY VIEW subscribed_movies
    AS SELECT mo.member_id, mb.full_name, mo.movie_title
         FROM movies AS mo
         INNER JOIN members AS mb
            ON mo.member_id = mb.id;

-- Create a temporary view over a CSV file so you can query it with SQL.
> CREATE TEMPORARY VIEW diamonds
    USING CSV
    OPTIONS (path '/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv',
             header 'true',
             mode 'FAILFAST');

> SELECT carat, cut, price FROM diamonds LIMIT 5;

-- Create a view with schema binding (default)
> CREATE TABLE emp(name STRING, income INT);
> CREATE VIEW emp_v WITH SCHEMA BINDING AS SELECT * FROM emp;

– The view ignores adding a column to the base table
> ALTER TABLE emp ADD COLUMN bonus SMALLINT;
> SELECT * FROM emp_v;
name  income
----  ------

-- The view tolerates narrowing the underlying type
> CREATE OR REPLACE TABLE emp(name STRING, income SMALLINT, bonus SMALLINT);
> SELECT typeof(income) FROM emp_v;
 INTEGER

– The view does not tolerate widening the underlying type
CREATE OR REPLACE TABLE emp(name STRING, income BIGINT, bonus SMALLINT);
> SELECT typeof(income) FROM emp_v;
 Error

– Create a view with SCHEMA COMPENSATION
> CREATE TABLE emp(name STRING, income SMALLINT, bonus SMALLINT);
> CREATE VIEW emp_v WITH SCHEMA COMPENSATION AS SELECT * FROM emp;

-- The view tolerates widening the underlying type but keeps its own signature fixed
CREATE OR REPLACE TABLE emp(name STRING, income INTEGER, bonus INTEGER);
> SELECT typeof(income) FROM emp_v;
 INTEGER

-- The view does not tolerate dropping a needed column
ALTER TABLE emp DROP COLUMN bonus;
> SELECT * FROM emp_v;
Error

– Create a view with SCHEMA EVOLUTION
> CREATE TABLE emp(name STRING, income SMALLINT);
> CREATE VIEW emp_v WITH SCHEMA EVOLUTION AS SELECT * FROM emp;

-- The view picks up additional columns
> ALTER TABLE emp ADD COLUMN bonus SMALLINT
> SELECT * FROM emp_v;
 name income bonus
 ---- ------ -----

-- The view picks up renamed columns as well
> ALTER TABLE emp RENAME COLUMN income TO salary SMALLINT;
> SELECT * FROM emp_v;
 name salary bonus
 ---- ------ -----

-- The view picks up changes to column types and dropped columns
> CREATE OR REPLACE TABLE emp(name STRING, salary BIGINT);
> SELECT *, typeof(salary)AS salary_type FROM emp_v;
 name salary
 ---- ------

-- Create a view using a default collation of UTF8_BINARY
> CREATE VIEW v DEFAULT COLLATION UTF8_BINARY
    AS SELECT 5::STRING AS text;

-- Creates a Metric View as specified in the YAML definition, with three dimensions and four measures representing the count of orders.
> CREATE OR REPLACE VIEW region_sales_metrics
  (month COMMENT 'Month order was made',
   status,
   order_priority,
   count_orders COMMENT 'Count of orders',
   total_Revenue,
   total_revenue_per_customer,
   total_revenue_for_open_orders)
  WITH METRICS
  LANGUAGE YAML
  COMMENT 'A Metric View for regional sales metrics.'
  AS $$
   version: 0.1
   source: samples.tpch.orders
   filter: o_orderdate > '1990-01-01'
   dimensions:
   - name: month
     expr: date_trunc('MONTH', o_orderdate)
   - name: status
     expr: case
       when o_orderstatus = 'O' then 'Open'
       when o_orderstatus = 'P' then 'Processing'
       when o_orderstatus = 'F' then 'Fulfilled'
       end
   - name: prder_priority
     expr: split(o_orderpriority, '-')[1]
   measures:
   - name: count_orders
     expr: count(1)
   - name: total_revenue
     expr: SUM(o_totalprice)
   - name: total_revenue_per_customer
     expr: SUM(o_totalprice) / count(distinct o_custkey)
   - name: total_revenue_for_open_orders
     expr: SUM(o_totalprice) filter (where o_orderstatus='O')
  $$;

> DESCRIBE EXTENDED region_sales_metrics;
  col_name                       data_type
  ------------------------------ --------------------------
  month                          timestamp
  status                         string
  order_priority                 string
  count_orders                   bigint measure
  total_revenue                  decimal(28,2) measure
  total_revenue_per_customer     decimal(38,12) measure
  total_revenue_for_open_orders  decimal(28,2) measure

  # Detailed Table Information
  Catalog                        main
  Database                       default
  Table                          region_sales_metrics
  Owner                          alf@melmak.et
  Created Time                   Thu May 15 13:03:01 UTC 2025
  Last Access                    UNKNOWN
  Created By                     Spark
  Type                           METRIC_VIEW
  Comment                        A Metric View for regional sales metrics.
  Use Remote Filtering           false
  View Text                      "
     version: 0.1
     source: samples.tpch.orders
     filter: o_orderdate > '1990-01-01'
     dimensions:
     - name: month
       expr: date_trunc('MONTH', o_orderdate)
     - name: status
       expr: case
         when o_orderstatus = 'O' then 'Open'
         when o_orderstatus = 'P' then 'Processing'
         when o_orderstatus = 'F' then 'Fulfilled'
         end
     - name: Order_Priority
       expr: split(o_orderpriority, '-')[1]
     measures:
     - name: count_orders
       expr: count(1)
     - name: total_Revenue
       expr: SUM(o_totalprice)
     - name: total_Revenue_per_Customer
       expr: SUM(o_totalprice) / count(distinct o_custkey)
     - name: Total_Revenue_for_Open_Orders
       expr: SUM(o_totalprice) filter (where o_orderstatus='O')
                                 "
  Language                       YAML
  Table Properties               [metric_view.from.name=samples.tpch.orders, metric_view.from.type=ASSET, metric_view.where=o_orderdate > '1990-01-01']

-- Create a parameterized metric view (requires DBR 18.2 and above)
-- The `discount` parameter is bound at query time and referenced in a measure.
> CREATE OR REPLACE VIEW discounted_sales_metrics
  WITH METRICS
  LANGUAGE YAML
  AS $$
   version: 1.1
   source: samples.tpch.orders
   parameters:
   - name: discount
     data_type: double
     default: 0
   dimensions:
   - name: order_priority
     expr: o_orderpriority
   measures:
   - name: discounted_revenue
     expr: SUM((1 - discount) * o_totalprice)
  $$;

-- Query the parameterized metric view, passing `discount` as a named argument
> SELECT order_priority, measure(discounted_revenue)
  FROM discounted_sales_metrics(discount => 0.15)
  GROUP BY ALL;

-- Omit the argument to use the default value of 0
> SELECT order_priority, measure(discounted_revenue)
  FROM discounted_sales_metrics
  GROUP BY ALL;

-- Tracking total_revenue_per_customer by month in 1995
> SELECT extract(month from month) as month,
    measure(total_revenue_per_customer)::bigint AS total_revenue_per_customer
  FROM region_sales_metrics
  WHERE extract(year FROM month) = 1995
  GROUP BY ALL
  ORDER BY ALL;
  month	 total_revenue_per_customer
  -----  --------------------------
   1     167727
   2     166237
   3     167349
   4     167604
   5     166483
   6     167402
   7     167272
   8     167435
   9     166633
  10     167441
  11     167286
  12     167542

-- Tracking total_revenue_per_customer by month and status in 1995
> SELECT extract(month from month) as month,
    status,
    measure(total_revenue_per_customer)::bigint AS total_revenue_per_customer
  FROM region_sales_metrics
  WHERE extract(year FROM month) = 1995
  GROUP BY ALL
  ORDER BY ALL;
  month  status      total_revenue_per_customer
  -----  ---------   --------------------------
   1     Fulfilled   167727
   2     Fulfilled   161720
   2    Open          40203
   2    Processing   193412
   3    Fulfilled    121816
   3    Open          52424
   3    Processing   196304
   4    Fulfilled     80405
   4    Open          75630
   4    Processing   196136
   5    Fulfilled     53460
   5    Open         115344
   5    Processing   196147
   6    Fulfilled     42479
   6    Open         160390
   6    Processing   193461
   7    Open         167272
   8    Open         167435
   9    Open         166633
   10   Open         167441
   11   Open         167286
   12   Open         167542