How to create a not null column in a view

前端 未结 2 1312
天命终不由人
天命终不由人 2020-12-20 13:24

Given a table like:

CREATE TABLE \"MyTable\" 
(
  \"MyColumn\" NUMBER NOT NULL
);

I want to create a view like:

CREATE VIEW         


        
2条回答
  •  礼貌的吻别
    2020-12-20 13:52

    If you could have a NOT NULL constraint on a view column I believe that a SELECT from the view would then fail if the column in question was NULL. If this is the intent then the following might give you what you're looking for:

    CREATE OR REPLACE VIEW some_view AS
      SELECT some_field,
             some_other_field,
             CASE
               WHEN field_of_interest IS NOT NULL
                 THEN CAST(field_of_interest AS BINARY_DOUBLE)
                 ELSE 1 / 0
             END AS field_of_interest_not_null
         FROM some_table;
    

    Not very attractive, and you get an ugly "ORA-01476: division is equal to zero" message if the ELSE branch of the CASE is taken, but perhaps it's a step on the road to "better".

    Share and enjoy.


    EDIT: If the objective is to only pick up rows where your target column is not null perhaps you could add a WHERE clause to your view, as in:

    CREATE OR REPLACE VIEW some_view AS
      SELECT some_field,
             some_other_field,
             CAST(field_of_interest AS BINARY_DOUBLE) AS field_of_interest
        FROM some_table
        WHERE field_of_interest IS NOT NULL;
    

    YMMV.


    EDIT2: Looking at the SQL Server example, it appears that the ISNULL function is being used to ensure that the column is never NULL. If this is acceptable you could do the following:

    CREATE OR REPLACE VIEW some_view AS
      SELECT some_field,
             some_other_field,
             CAST(NVL(field_of_interest, 0.0) AS BINARY_DOUBLE) AS field_of_interest
        FROM some_table
        WHERE field_of_interest IS NOT NULL;
    

    To quote Bullwinkle, "This time fer sure!!!" :-)

提交回复
热议问题