获取已连接用户的真实身份

时间:2018-04-24 05:43:26

标签: sql-server delphi unidac

  

dxStatusbar1.Panels 1。文字:=   DataModule2.UniConnectDialog1.Connection.Username;

...给我连接到sql server的用户名。 但是,连接的用户在实际数据库中具有不同的名称。

实施例: 他的sql server登录名是' John'用户映射到' Northwind'数据库。 但是在Northwind'数据库他被称为约翰史密斯'。 这是我试图在dxStatusbar1.Panels 1中显示的名称(John Smith)。 在他连接之后。

我怎么能得到它?

编辑: 试过维多利亚的建议:

UserName := DataModule2.UniConnection1.ExecSQL('SELECT :Result = CURRENT_USER', ['Result']);
 dxStatusbar1.Panels[1].Text := UserName; 

但得到:

enter image description here

2 个答案:

答案 0 :(得分:2)

我找不到任何UniDAC API方法来获取当前连接的用户名(甚至不是SDAC),所以我只发出一个查询CURRENT_USER的SQL命令并从结果中获取名称:

SELECT CURRENT_USER;

使用 USER 功能的Unified SQL方式:

SELECT {fn USER};

由于您在评论中提到了存储过程,因此我觉得您可能希望直接从连接对象获取此信息而不使用查询对象。如果是这样,您甚至不需要存储过程,而是直接执行如下命令:

var
  UserName: string;
begin
  UserName := UniConnection1.ExecSQL('SELECT :Result = CURRENT_USER', ['Result']);
  ...
end;

或以统一的方式:

var
  UserName: string;
begin
  UserName := UniConnection1.ExecSQL('SELECT :Result = {fn USER}', ['Result']);
  ...
end;

答案 1 :(得分:0)

其中一个可能会为你完成这项工作。避风港经过测试。

SELECT ORIGINAL_LOGIN()
SELECT SYSTEM_USER
SELECT SUSER_SNAME()

希望它有所帮助。

ORIGINAL_LOGIN:Returns the name of the login that connected to the instance of SQL Server. You can use this function to return the identity of the original login in sessions in which there are many explicit or implicit context switches.

SYSTEM_USER:Allows a system-supplied value for the current login to be inserted into a table when no default value is specified.

SUSER_SNAME:Returns the login name associated with a security identification number (SID).