使用liquibase修改sql server中的数据类型和数据

7eumitmz  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(869)

我有一张table temp 在使用liquibase创建的sql server中
表的分解更改日志 temp

databaseChangeLog:
  - changeSet:
      author: Author_name
      id: create_temp_table
      createTable:
        tableName: temp
        columns:
          - column:
              name: id
              type: BIGINT
              constraints:
                primaryKey: 'true'
          - column:
              name: type
              type: VARCHAR(255)
          - column:
              name: reference
              type: VARCHAR(255)
          - column:
              name: rate
              type: VARCHAR(255)

我想修改 rate 从字符串到小数的列。所以我在下面创建了一个新的changelog文件

databaseChangeLog:
  - changeSet:
      id: modify_column_temp_table
      author: Author_name
      changes:
        - modifyDataType:
            columnName: rate
            newDataType: DECIMAL(18,4)
            tableName: temp

现在,数据库中已经有了一些现有的数据 temp 带的表格 rate 列作为字符串。当 modify_column_temp_table 当changelog运行时,我知道sqlserver会抛出一个cast错误,说string不能从cat到decimal。
如何在同一个changelog中执行脚本或命令,实际修改列的数据和数据类型,以便 rate 是否修改为新的数据类型?

vd8tlhqk

vd8tlhqk1#

这是一个常见的情况,它有一个众所周知的决定。您应该创建几个变更集,逐步修改数据库。
使用新名称重命名原始列:

<changeSet id="rename column" author="authorName" failOnError="true">
        <preConditions>
            <columnExists tableName="temp" columnName="rate"/>
            <!-- if you also wanna check the column type use <sqlCheck> with database-dependent syntax -->
        </preConditions>
        <renameColumn oldColumnName="rate" newColumnName="rate_number" tableName="temp"/>
    </changeSet>

创建具有新数据类型的列:

<changeSet id="create new column" author="authorName" failOnError="true">
        <preConditions>
            <columnExists tableName="temp" columnName="rate_number"/>
            <not>
                <columnExists tableName="temp" columnName="rate"/>
            </not>
        </preConditions>
        <addColumn tableName="temp">
            <column name="rate" type="NUMBER(38,0)"/>
        </addColumn>
    </changeSet>

使用特定于数据库的功能移动和转换数据:

<changeSet id="copy data" author="authorName" failOnError="true">
        <preConditions>
            <columnExists tableName="rate" columnName="rate"/>
            <columnExists tableName="rate" columnName="rate_number"/>
        </preConditions>
        <sql>
            <!-- your database-specific sql code for copy and transform data -->
        </sql>
    </changeSet>

如果希望在工作流中使用回滚功能,可以添加语句。另外,您可以添加forth changeset来删除名为“rate\u number”的列,但是在删除此列之前测试应用程序可能会很有用。
这里的任何ddl语句都需要不同的变更集,因为ddl语句的执行提交了当前事务,并且不能回滚。因此,在更新过程中,应该手动处理liquibase下降的情况。

相关问题