[英]How can i Alter TABLE all column from not null to null by one query of PostgreSQL 9.1
I migrate my data from MySQL Database to PostgreSQL Database and by mistaken i have all my column set not-null in PostgreSQL database. 我将数据从MySQL数据库迁移到PostgreSQL数据库,并且错误地将所有列设置为PostgreSQL数据库中的非空值。
After this i am facing issue for inserting data and have to uncheck not null manually, so is there any way to do for all column in table ( except id(PRIMARY KEY) ). 在此之后,我面临插入数据的问题,必须手动取消选中不为null的问题,因此表中的所有列都可以进行任何处理(id(PRIMARY KEY)除外)。
i have this query also for single column but its also time consuming, 我对单列也有此查询,但也很耗时,
ALTER TABLE <table name> ALTER COLUMN <column name> DROP NOT NULL;
I don't think there is built in functionality for this. 我认为没有内置功能。 But it's easy to write a function to do this.
但是编写一个函数来做到这一点很容易。 For example:
例如:
CREATE OR REPLACE FUNCTION set_nullable(relation TEXT)
RETURNS VOID AS
$$
DECLARE
rec RECORD;
BEGIN
FOR rec IN (SELECT * FROM pg_attribute
WHERE attnotnull = TRUE AND attrelid=relation::regclass::oid AND attnum > 0 AND attname != 'id')
LOOP
EXECUTE format('ALTER TABLE %s ALTER COLUMN %s DROP NOT NULL', relation, rec.attname);
RAISE NOTICE 'Set %.% nullable', relation, rec.attname;
END LOOP;
END
$$
LANGUAGE plpgsql;
Use it like this: 像这样使用它:
SELECT set_nullable('my_table');
Just perform a new CREATE TABLE noNULL
using the same structure as your current table and modify the NULLable
field you need. 只需使用与当前表相同的结构执行新的
CREATE TABLE noNULL
,然后修改所需的NULLable
字段即可。
Then insert from old table 然后从旧表插入
INSERT INTO noNULL
SELECT *
FROM oldTable
then delete oldTable
and rename noNull -> oldTable
然后删除
oldTable
并重命名noNull -> oldTable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.