0

If a Cloud Spanner table is created with nullable columns, is it possible to add a NOT NULL constraint on a column without recreating the table?

4

3 回答 3

0

不幸的是,没有办法添加非空列

这样做的方法:

1 添加可空列

ALTER TABLE table1 ADD COLUMN column1 STRING(255)
  1. UPDATE table1.column1,SET NOT NULL VALUE 到列(如果表不为空)。
UPDATE TABLE table1 SET column1 = "<GENERATED DATA>"
  1. 添加约束
ALTER TABLE table1 ADD COLUMN column1 STRING(255) NOT NULL

谢谢。

于 2020-06-25T16:15:13.887 回答
0

You can add a NOT NULL constraint to a non-key column. You must first ensure that all rows actually do have values for the column. Spanner will scan the data to verify before fully applying the NOT NULL constraint. More information about how to alter tables is here and here.

However, you can not add such a constraint to a key column. That kind of change would require rewriting all the data in the table, because the nullness of the key affects how the data is encoded. The only option for making that change is to create a new table that's set up the way you want, make code changes to support using both tables temporarily, gradually move the data from the old table to the new table, and eventually change the code to use only the new table and drop the old table. If you further then wanted the original table name, you'd have to do the whole thing again.

于 2017-02-16T20:43:27.280 回答
0

在现有表的扳手中创建可为空的列通常是一个三步过程......

# add new column to table
ALTER TABLE <table_name> ADD COLUMN <column_name> <value_type>;

# create default values
UPDATE <table_name> SET <column_name>=<default_value> WHERE TRUE;

# add constraint
ALTER TABLE <table_name> ALTER COLUMN <column_name> <value_type> NOT NULL;
于 2021-05-28T16:16:09.190 回答