![](/img/trans.png)
[英]postgresql/psql query where clause multiple “or” read from file
[英]PostgreSQL: how to efficiently alter multiple columns from psql?
我有幾個布爾列的PostgreSQL表,目前只包含true或null。 我想對所有人做以下事情:
not null
約束 即:
-- for each column specified:
update my_table set my_column = 'f' where my_column is null;
alter table my_table alter column my_column set default 'f';
alter table my_table alter column my_column set not null;
是否有psql(或標准SQL)的功能將迭代指定的列列表並對每個列應用一系列操作?
你不能遍歷所有列,但為了安全起見,你可能不想這樣做但是指定哪些要改變自己。 另一種方法是執行腳本查詢列名稱然后更改它們。
要更改它們,請使用ALTER TABLE
。 請參閱PgSQL文檔: http : //www.postgresql.org/docs/8.4/static/sql-altertable.html
ALTER TABLE xy ALTER COLUMN a SET DEFAULT FALSE, ALTER COLUMN b SET NOT NULL
等等
這樣做,因為VARIADIC需要8.4或更高版本。
CREATE OR REPLACE FUNCTION setdefaults(
IN _tname TEXT, -- tablename to alter
VARIADIC _cname TEXT[] -- all columnnames to alter
)
RETURNS boolean
LANGUAGE plpgsql
AS
$$
DECLARE
row record;
BEGIN
FOR row IN SELECT unnest(_cname) AS colname LOOP
EXECUTE 'ALTER TABLE ' || quote_ident(_tname) || ' ALTER COLUMN ' || quote_ident(row.colname) || ' SET DEFAULT false;';
EXECUTE 'UPDATE ' || quote_ident(_tname) || ' SET ' || quote_ident(row.colname) || ' = DEFAULT WHERE ' || quote_ident(row.colname) || ' IS NULL;';
EXECUTE 'ALTER TABLE ' || quote_ident(_tname) || ' ALTER COLUMN ' || quote_ident(row.colname) || ' SET NOT NULL;';
END LOOP;
RETURN TRUE;
END;
$$;
SELECT setdefaults('foo', 'x','y','z'); -- alter table "foo"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.