使用liquibase修改SQL Server中的数据类型和数据



我在SQL server中使用liquibase创建了一个表temp

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列从字符串修改为十进制。所以我在下面创建了一个新的变更日志文件

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变更日志运行时,我知道SQl服务器会抛出一个强制转换错误,说字符串不能是cat到decimal。

如何在同一个变更日志中执行一个脚本或命令,该脚本或命令实际上会修改列的数据和数据类型,以便将rate中的现有数据修改为新的数据类型?

这是一种常见的情况,它有一个众所周知的决定。您应该创建几个变更集来逐步修改数据库。

  1. 使用新名称重命名原始列:
<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>
  1. 创建具有新数据类型的列:
<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>
  1. 使用特定于数据库的功能移动和转换数据:
<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>

如您所愿,您可以添加<回滚>语句,如果您希望在工作流中使用回滚功能。此外,您可以添加第四个变更集,该变更集删除名为"的列;rate_number";但是在删除此列之前测试应用程序可能是有用的。

这里的任何DDL语句都需要不同的变更集,因为DDL语句的执行会提交当前事务,并且不能回滚。因此,在更新过程中,您应该手动处理liquibase掉落的情况。

相关内容

最新更新