简体   繁体   中英

Adding a new column in a temporary table

I have a temporary table in a PostgreSQL function and I want to insert a new VARCHAR column. It should have a value that depends on another column of the table, named "amount".

When the amount is positive I would like the value of the column row to be credit and when the value is negative the column should be debit.

I have one more request: I want to round the value of amount column in 2 decimal digits

You want ALTER TABLE ... ADD COLUMN followed by an UPDATE .

I initially said ALTER TABLE ... ADD COLUMN ... USING but that was wrong on two counts. ADD COLUMN takes a DEFAULT not USING - and You can't do it in one pass because neither a DEFAULT expression nor a USING expression may not refer to other columns.

So you must do:

 ALTER TABLE tablename ADD COLUMN colname varchar;
 UPDATE tablename SET colname = ( CASE WHEN othercol < 0 THEN 'Credit' ELSE 'Debit' END );

Think carefully about whether zero should be 'Debit' or 'Credit' and adjust the CASE accordingly.

For rounding, use round(amount,2) . There isn't enough detail in your question for me to be sure how; probably by UPDATE ing the temp table with UPDATE thetable SET amount = round(amount,2) but without the context it's hard to know if that's right. That statement irreversibly throws information away so it should only be used on a copy of the data.

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