oracle11gsql-insert

INSERT INTO with validated (limited) values


I think this is rather trivial, but I lost the way ..

SQL, Oracle 11 - a simple statement:

   INSERT INTO NEW_TABLE (A, B, NEW_LENGTH)
      SELECT
         A, B, OLD_LENGTH
      FROM
         OLD_TABLE

in "old_length" I have values from "-100 to 100", but in "new_length" the values are limited from "-50 to 50". A simple "insert" gives an error "value too big for the column", so I have to use only allowed values. Values too big should be replaced with null.

Is there a simple way to achieve it? I tried with NVL2 and DECODE, but got only some syntax errors.

Thanks for advice in advance!


Solution

  • You can use a case expression:

       INSERT INTO NEW_TABLE (A, B, NEW_LENGTH)
          SELECT
             A, B,
                CASE
                   WHEN OLD_LENGTH >= -50 AND OLD_LENGTH <= 50
                   THEN OLD_LENGTH
                END
          FROM
             OLD_TABLE
    

    fiddle

    A case expression has an implicit ELSE NULL if you don't specify your own ELSE value, but you may prefer to include that for completeness.