无法在 Sqlite3 中添加默认值为 NULL 的 NOT NULL 列

Cannot add a NOT NULL column with default value NULL in Sqlite3(无法在 Sqlite3 中添加默认值为 NULL 的 NOT NULL 列)
本文介绍了无法在 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 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
FastAPI + Tortoise ORM + FastAPI Users (Python) - Relationship - Many To Many(FastAPI+Tortoise ORM+FastAPI用户(Python)-关系-多对多)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)
Inserting NaN value into MySQL Database(将NaN值插入MySQL数据库)