在触发器上获取当前用户的会话

时间:2015-09-24 10:41:57

标签: sql sql-server triggers

我在SQL Server上构建了一个触发器来跟踪表的删除和更新。但是CURRENT_USER变量返回dbo而不是我通过sql客户端(C#接口程序)登录的用户。我正在使用Windows身份验证方法(SSPI)与Active Directory用户权限。 所以客观是这样的:

create trigger fatura_historico_deleted
on Fatura
for delete
as
begin
    declare
        @id_fa int,
        @cod_fa nvarchar(100),
        @now datetime,
        @id_empr int,
        @data date,
        @preco money,
        @tipo nvarchar(50),
        @utilizador varchar(100),
        @ação varchar(30);
    SELECT
        @id_fa=id_fatura,
        @cod_fa=cod_fatura,
        @id_empr=id_empresa,
        @data = Data,
        @preco = Preço,
        @tipo = Tipo,
        @now=GETDATE(),
        @utilizador=CURRENT_USER, --THIS IS RETURNING 'dbo'
        @ação='Eliminado'
    FROM
        deleted
    insert into Fatura_Histórico(
        id_fatura,
        cod_fatura,
        id_empresa,
        Data,
        Preço,
        Tipo,
        Data_Registo,
        Utilizador,
        Ação
    ) values(
        @id_fa,
        @cod_fa,
        @id_empr,
        @data,
        @preco,
        @tipo,
        @now,
        @utilizador,
        @ação
    );
end

是否有让用户删除或更新或触发此触发器的用户?

2 个答案:

答案 0 :(得分:2)

如果您是dboCURRENT_USER将始终返回dbo。如果您处于execute as上下文中,则suser_name()system_user将返回您假冒的用户。

使用original_login()返回实际用户。

use tempdb;
go
SELECT CURRENT_USER, system_user, suser_name(), original_login();
GO
EXECUTE AS USER = 'guest';
GO
SELECT CURRENT_USER, system_user, suser_name(), original_login();
GO
REVERT;
GO
SELECT CURRENT_USER, system_user, suser_name(), original_login();
GO

答案 1 :(得分:1)

尝试SYSTEM_USER,它对我有用