SQL CURRENT_USER
CURRENT_USER is standard SQL, but what it returns differs: a database user on SQL Server, a role on PostgreSQL, an account with a host on MySQL.
- Категория
- System & session
- Returns
text- In this category
- 4 of 13
Синтаксис
CURRENT_USER
SESSION_USER
CURRENT_USER() -- MySQL
USER -- Oracle
Each block is a separate form. The support table and the examples show which engine takes which.
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Да | CURRENT_USER is the database user (dbo for sysadmins); SUSER_SNAME() is the login |
| PostgreSQL | Да | CURRENT_USER and SESSION_USER, written without parentheses |
| MySQL | Да | CURRENT_USER() is the account that authenticated; USER() is what the client sent |
| SQLite | Not built in | no users |
| Oracle | Different name or syntax | USER or SYS_CONTEXT('USERENV', 'CURRENT_USER'); CURRENT_USER is not valid in SQL |
Примеры
SQL Server
SELECT CURRENT_USER AS db_user, SUSER_SNAME() AS login_name; -- dbo, sa when connected as sa
PostgreSQL
SELECT current_user, session_user;
MySQL
SELECT USER(), CURRENT_USER();
Oracle
SELECT USER, SYS_CONTEXT('USERENV', 'SESSION_USER') AS session_user FROM dual;
Полезно знать
- SQL Server tracks two identities. CURRENT_USER returns the database user, which is dbo for every sysadmin login; SUSER_SNAME() returns the login itself, such as sa or a Windows account. Audit columns usually want the login.
- In PostgreSQL CURRENT_USER and SESSION_USER are keywords, so CURRENT_USER() is a syntax error. They differ after SET ROLE, and inside a SECURITY DEFINER function CURRENT_USER is the function's owner.
- MySQL's USER() is the user and host the client claimed; CURRENT_USER() is the account row that matched, which can be a wildcard-host account such as app@'%'.
- Oracle rejects SELECT CURRENT_USER FROM dual with ORA-00904. Use USER, or SYS_CONTEXT('USERENV', 'SESSION_USER').
Questions about CURRENT_USER
How do I record who changed a row?
Use a column default or a trigger. PostgreSQL: DEFAULT CURRENT_USER. SQL Server: DEFAULT SUSER_SNAME(). Oracle: DEFAULT USER. MySQL 8.0.13+ accepts an expression default such as DEFAULT (CURRENT_USER()).
Why does CURRENT_USER return dbo on SQL Server?
Members of sysadmin map to the dbo user in every database. Call SUSER_SNAME() or ORIGINAL_LOGIN() to see the login that actually connected.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.