简体   繁体   中英

Add a new column to a view in SQL

I have a database and I've made a view with the data I want. The data looks something like this:

    n     |   value |
----------+---------+
 50404791 |     112 | 
  5034591 |     164 |
 50280287 |      31 |

I want to add a column of text like this:

    n     |   value | status |
----------+---------+--------+
 50404791 |     112 |default | 
  5034591 |     164 |biggest |
 50280287 |      31 |smallest|

I tried Alter Table Table1 Add Column status text ; but it seems like text is not a data type. Any suggestions what to do?

Tested on Rextester.com (remember, avoid anyway to use SELECT * in a view)

CREATE TABLE TABLE1 (ID INTEGER);
CREATE VIEW V1 AS SELECT * FROM TABLE1;
INSERT INTO TABLE1 VALUES (0);

ALTER TABLE TABLE1 ADD COLUMN STATUS TEXT;    
INSERT INTO TABLE1 (ID, STATUS) VALUES (1, 'aaa');

SELECT * FROM V1;
DROP VIEW V1;

CREATE VIEW V1 AS SELECT * FROM TABLE1;
SELECT * FROM V1;

Output:

    id
1   0
2   1

    id  status
1   0   NULL
2   1   aaa

You'll need to drop and re-create the view - you can't alter an existing view. And yes, text IS a data type.

In Postgres you can use CREATE OR REPLACE without dropping the view and do the following

    CREATE OR REPLACE VIEW View1 AS
        SELECT value, status FROM Table 1;

Altering the original table will just alter that table without changes to the view.

I found answer on postgresql.org

You can do from pgAdmin by right-clicking on the view and select CREATE SCRIPT uncomment: DROP VIEW ; and edit the CREATE VIEW to drop the column.

However if the view is used in other views you have to drop them all and recreate in sequence.

Alternatively you can delete the columns from the pg_catalog.pg_attribute table. Make sure however that you know you deleting only the one's you want to delete and not other tables columns... using the below:

delete from pg_attribute where attrelid = regclass 'yourviewname' and attname = 'columnnametodrop'

Best to first do couple of selects until you have the selection correct:

select attrelid::regclass as whatever, * from pg_attribute where attname = 'columnnametodrop'

Johan Nel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM