Error: ORA-01758: table must be empty to add mandatory ,NOT NULL column [Failed SQL:

这个报错原因是表中已经有数据了!

我们经常会遇到这种情况:

项目已经部署给用户用了,但是某张表需要改动字段,这时候就需要打补丁了。

1、打补丁增加字段时,如果在开发环境下进行清库开发测试时,是完全没有问题的,因为开发环境下清库测试时,数据库是空数据的,所以不会报标题的那个错误。

2、但是,如果打补丁增加的字段是不可为空的,如果没有设置默认值,那么在部署的时候就会报那个错误,因为以前部署的版本已经有数据了,部署新版本的时候是不能清库的,

所以增加的字段是不可为空的,那么就需要打补丁的时候设置字段的默认值,如果不设置默认值并且数据库有数据,那么就会报错!

这是我在实际开发中遇到过的问题。

xml打补丁设置默认值defaultValue

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet  author="Xxxx">

        <addColumn tableName="groot_fytjxxbqj">
            <column name="ltshqk" type="varchar2(20)" defaultValue="UNREVIEW">
                <constraints nullable="false"/>
            </column>
            <column name="sbshqk" type="varchar2(20)" defaultValue="UNREVIEW">
                <constraints nullable="false"/>
            </column>
            <column name="cwshqk" type="varchar2(20)" defaultValue="UNREVIEW">
                <constraints nullable="false"/>
            </column>
        </addColumn>
  </changeSet>
</databaseChangeLog>