简体   繁体   中英

Oracle SQL alter table add column with current user name

It was a 2 part question and I got the timestamp correctly. I'm on 12C and trying to do something like:

ALTER TABLE customers
    ADD modified_by (USER FROM DUAL);

Basically just columns in a table that show who modified the table and at what time they did so.

I also tried

ALTER TABLE customers
    ADD last_modified TIMESTAMP;
ALTER TABLE customers
    ADD modified_by USER;

and other combinations of keywords that I found on this site and other sites but none of them work.

We only learned dual in class but I'm looking for any way to do these.

Edit:

I now understand what was taught to me by the user with almost 1 million points.

Still unsure how to do the username. Read this: https://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_2114.htm#REFRN20302

and tried:

ALTER TABLE customers
    ADD modified_by USERNAME;

doesn't work get invalid datatype.

Then saw this: https://www.techonthenet.com/oracle/questions/find_users.php

and tried:

ALTER TABLE customers
    ADD modified_by USERNAME FROM DBA_USERS;

but getting invalid alter table option. SQL is hard.

If you read through the Oracle documentation on virtual columns, you will find this:

Functions in expressions must be deterministic at the time of table creation, but can subsequently be recompiled and made non-deterministic

A deterministic function is one that returns the same value when it is passed the same arguments. The expressions that you are using contain non-deterministic functions. Hence, they are not allowed.

The error that I get when I try this is:

ORA-54002: only pure functions can be specified in a virtual column expression

For some unknown reason, Oracle equates "pure" with "deterministic" in the error message. But this is saying that the function needs to be deterministic.

After you edited the question, it seems that you are somewhat closer to what you want. This:

ALTER TABLE customers ADD modified_by VARCHAR2(30);
                                      ^^^^^^^^^^^^
                                      datatype goes here, not what you'd like
                                      to put into this column

Then, during inserts or updates of that table, you'd put USER in there, eg

insert into customers (id, modified_by) values (100, USER);

Or, probably even better, set it to be default, as @a_horse_with_no_name suggested:

ALTER TABLE customers ADD modified_by VARCHAR2(30) DEFAULT USER;

so - if you don't explicitly put anything into that column, it'll be populated with the USER function's value.

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