Cannot add a NOT NULL column with default value NULL in Sqlite3(无法在 Sqlite3 中添加默认值为 NULL 的 NOT NULL 列)
问题描述
我在尝试向现有表添加 NOT NULL 列时收到以下错误.为什么会这样?.我试过 rake db:reset 认为现有记录是问题所在,但即使在重置数据库后,问题仍然存在.你能帮我解决这个问题吗.
I am getting the following error while trying to add a NOT NULL column to an existing table. Why is it happening ?. I tried rake db:reset thinking that the existing records are the problem, but even after resetting the DB, the problem persists. Can you please help me figure this out.
迁移文件
class AddDivisionIdToProfile < ActiveRecord::Migration
def self.up
add_column :profiles, :division_id, :integer, :null => false
end
def self.down
remove_column :profiles, :division_id
end
end
错误信息
SQLite3::SQLException: 无法添加默认值为 NULL 的 NOT NULL 列:ALTER TABLE "profiles" ADD "division_id" integer NOT NULL
SQLite3::SQLException: Cannot add a NOT NULL column with default value NULL: ALTER TABLE "profiles" ADD "division_id" integer NOT NULL
推荐答案
表中已有行,并且要添加新列 division_id.它需要在每个现有行的新列中添加一些内容.
You already have rows in the table, and you're adding a new column division_id. It needs something in that new column in each of the existing rows.
SQLite 通常会选择 NULL,但您已指定它不能为 NULL,那么它应该是什么?它无从得知.
SQLite would typically choose NULL, but you've specified it can't be NULL, so what should it be? It has no way of knowing.
见:
- 在 Rails 迁移中添加没有默认值的非空列(2009 年,不再可用,因此这是存档快照.组织)
- 添加非空列到现有表(2014)
- Adding a Non-null Column with no Default Value in a Rails Migration (2009, no longer available, so this is a snapshot at archive.org)
- Adding a NOT NULL Column to an Existing Table (2014)
那个博客的建议是添加没有not null约束的列,每行都会添加NULL.然后你可以在division_id中填入值,然后使用change_column来添加not null约束.
That blog's recommendation is to add the column without the not null constraint, and it'll be added with NULL in every row. Then you can fill in values in the division_id and then use change_column to add the not null constraint.
有关执行此三步过程的迁移脚本的说明,请参阅我链接到的博客.
See the blogs I linked to for an description of a migration script that does this three-step process.
这篇关于无法在 Sqlite3 中添加默认值为 NULL 的 NOT NULL 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法在 Sqlite3 中添加默认值为 NULL 的 NOT NULL 列
基础教程推荐
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 在多列上分布任意行 2021-01-01
