AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 168102
Accepted
i-one
i-one
Asked: 2017-03-25 07:28:49 +0800 CST2017-03-25 07:28:49 +0800 CST 2017-03-25 07:28:49 +0800 CST

Acionador DDL para ALTER_AUTHORIZATION

  • 772

Eu preciso realizar alguma auditoria, quando mudar de propriedade segura, como

ALTER AUTHORIZATION ON SCHEMA::[SchemaName] TO [PrincipalName];

acontece no banco de dados.

O gatilho DDL do escopo do banco de dados parece ser um mecanismo apropriado para essa finalidade. Na documentação (seção DDL Statements That Have Server or Database Scope ) vejo que deve haver ALTER_AUTHORIZATIONevent.

No entanto, quando estou tentando criar um DDL-trigger apropriado

CREATE TRIGGER [OnAlterAuthorization] ON DATABASE
FOR ALTER_AUTHORIZATION
AS
BEGIN
    PRINT 'Perform audit';
END

Estou recebendo erro Msg 1084

Msg 1084, Level 15, State 1, Procedure OnAlterAuthorization, Line 2 [Batch Start Line 0] 'ALTER_AUTHORIZATION' é um tipo de evento inválido.

Dentrosys.event_notification_event_types

SELECT type_name
FROM sys.event_notification_event_types
WHERE type_name LIKE 'ALTER_AUTHOR%';

não há nenhum ALTER_AUTHORIZATIONevento, apenas

type_name
-----------------------------
ALTER_AUTHORIZATION_SERVER
ALTER_AUTHORIZATION_DATABASE

deles ALTER_AUTHORIZATION_SERVERnão atende obviamente, e ALTER_AUTHORIZATION_DATABASEde acordo com a documentação

Aplica-se à instrução ALTER AUTHORIZATION quando ON DATABASE é especificado

Então, a questão é. Onde está ALTER_AUTHORIZATIONprometido na documentação? Como posso pegar a mudança de uma propriedade segura no banco de dados?

sql-server trigger
  • 2 2 respostas
  • 508 Views

2 respostas

  • Voted
  1. Dave Mason
    2017-03-25T12:04:51+08:002017-03-25T12:04:51+08:00

    Me deparei com o mesmo problema que você. Eu continuaria descobrindo que as Notificações de Eventos podem ser usadas para lidar com o AUDIT_CHANGE_DATABASE_OWNERevento. (Observe que esse evento não pode ser usado com um gatilho DDL.) Eu escrevi um artigo de blog Event Notifications que por acaso usa o AUDIT_CHANGE_DATABASE_OWNERevento como exemplo: SQL Server Event Handling: Event Notifications

    Abaixo está um script que pode ajudá-lo a começar.

    USE SomeDatabase
    GO
    
    --Create a queue just for change db owner events.
    CREATE QUEUE queChangeDBOwnerNotification
    
    --Create a service just for change db owner events.
    CREATE SERVICE svcChangeDBOwnerNotification
    ON QUEUE queChangeDBOwnerNotification ([http://schemas.microsoft.com/SQL/Notifications/PostEventNotification])
    
    -- Create the event notification for change db owner events on the service.
    CREATE EVENT NOTIFICATION enChangeDBOwner
    ON SERVER
    WITH FAN_IN
    FOR AUDIT_CHANGE_DATABASE_OWNER
    TO SERVICE 'svcChangeDBOwnerNotification', 'current database';
    GO
    
    CREATE PROCEDURE dbo.ReceiveChangeDBOwner
    AS
    BEGIN
        SET NOCOUNT ON
        DECLARE @MsgBody XML
    
        WHILE (1 = 1)
        BEGIN
            BEGIN TRANSACTION
    
            -- Receive the next available message FROM the queue
            WAITFOR (
                RECEIVE TOP(1) -- just handle one message at a time
                    @MsgBody = CAST(message_body AS XML)
                    FROM queChangeDBOwnerNotification
            ), TIMEOUT 1000  -- if the queue is empty for one second, give UPDATE and go away
            -- If we didn't get anything, bail out
            IF (@@ROWCOUNT = 0)
            BEGIN
                ROLLBACK TRANSACTION
                BREAK
            END 
            ELSE
            BEGIN
                --Interrogate the event data for relevant properties/values.
                DECLARE @Cmd VARCHAR(1024)
                DECLARE @MailBody NVARCHAR(MAX)
                DECLARE @Subject NVARCHAR(255)
    
                SET @Cmd = @MsgBody.value('(/EVENT_INSTANCE/TextData)[1]', 'VARCHAR(1024)')
                SET @Subject = @@SERVERNAME + ' -- ' + @MsgBody.value('(/EVENT_INSTANCE/EventType)[1]', 'VARCHAR(128)' )    
    
                --Build an html table for use with an html-formatted email message.
                SET @MailBody = 
                    '<table border="1">' +
                    '<tr><td>Server Name</td><td>' + @MsgBody.value('(/EVENT_INSTANCE/ServerName)[1]', 'VARCHAR(128)' ) + '</td></tr>' + 
                    '<tr><td>Start Time</td><td>' + @MsgBody.value('(/EVENT_INSTANCE/StartTime)[1]', 'VARCHAR(128)' ) + '</td></tr>' +  
                    '<tr><td>Session Login Name</td><td>' + @MsgBody.value('(/EVENT_INSTANCE/SessionLoginName)[1]', 'VARCHAR(128)' ) + '</td></tr>' + 
                    '<tr><td>Login Name</td><td>' + @MsgBody.value('(/EVENT_INSTANCE/LoginName)[1]', 'VARCHAR(128)') + '</td></tr>' + 
                    '<tr><td>Windows Domain\User Name</td><td>' + @MsgBody.value('(/EVENT_INSTANCE/NTDomainName)[1]', 'VARCHAR(256)') + '\' +
                        @MsgBody.value('(/EVENT_INSTANCE/NTUserName)[1]', 'VARCHAR(256)') + '</td></tr>' +  
                    '<tr><td>DB User Name</td><td>' + @MsgBody.value('(/EVENT_INSTANCE/DBUserName)[1]', 'VARCHAR(128)' ) + '</td></tr>' + 
                    '<tr><td>Host Name</td><td>' + @MsgBody.value('(/EVENT_INSTANCE/HostName)[1]', 'VARCHAR(128)' ) + '</td></tr>' +  
                    '<tr><td>Application Name</td><td>' + @MsgBody.value('(/EVENT_INSTANCE/ApplicationName)[1]', 'VARCHAR(128)' ) + '</td></tr>' + 
                    '<tr><td>Command Succeeded</td><td>' + @MsgBody.value('(/EVENT_INSTANCE/Success)[1]', 'VARCHAR(8)' ) + '</td></tr>' + 
                    '</table><br/>' +
                    '<p><b>Text Data:</b><br/>' + REPLACE(@Cmd, CHAR(13) + CHAR(10), '<br/>') +'</p><br/>'
                --PRINT @Subject
                --PRINT @MailBody
    
                --Note: you may need to set [msdb] to trustworthy for this to work.
                --Another option is to sign a stored proc with a certificate.
                --See: https://learn.microsoft.com/en-us/sql/relational-databases/tutorial-signing-stored-procedures-with-a-certificate
                EXEC msdb.dbo.sp_send_dbmail 
                    @recipients = '[email protected]', 
                    @subject = @Subject,
                    @body = @MailBody,
                    @body_format = 'HTML',
                    @exclude_query_output = 1
                /*
                    Commit the transaction.  At any point before this, we 
                    could roll back -- the received message would be back 
                    on the queue AND the response wouldn't be sent.
                */
                COMMIT TRANSACTION
            END
        END
    END
    GO
    
    ALTER QUEUE dbo.queChangeDBOwnerNotification 
    WITH 
        STATUS = ON, 
        ACTIVATION ( 
            PROCEDURE_NAME = dbo.ReceiveChangeDBOwner, 
            STATUS = ON, 
            MAX_QUEUE_READERS = 1, 
            EXECUTE AS OWNER) 
    GO
    
    • 1
  2. Best Answer
    i-one
    2017-03-29T01:55:19+08:002017-03-29T01:55:19+08:00

    Descobri que apesar desse evento ALTER_AUTHORIZATION_DATABASEde acordo com a documentação ser declarado como

    Aplica-se à instrução ALTER AUTHORIZATION quando ON DATABASE é especificado

    ele é acionado não apenas quando o proprietário do banco de dados é alterado, mas também quando o proprietário de uma alteração protegível no banco de dados.

    Em outras palavras, o gatilho DDL

    CREATE TRIGGER [OnAlterAuthorization] ON DATABASE
    FOR ALTER_AUTHORIZATION_DATABASE
    AS
    BEGIN
        PRINT 'Check ownership';
    END
    

    funciona não só para

    ALTER AUTHORIZATION ON DATABASE::[DbName] TO [PrincipalName];
    

    Mas por exemplo para

    ALTER AUTHORIZATION ON SCHEMA::[SchemaName] TO [PrincipalName];
    

    ou

    ALTER AUTHORIZATION ON ROLE::[RoleName] TO [PrincipalName];
    

    também.

    • 0

relate perguntas

  • SQL Server - Como as páginas de dados são armazenadas ao usar um índice clusterizado

  • Preciso de índices separados para cada tipo de consulta ou um índice de várias colunas funcionará?

  • Quando devo usar uma restrição exclusiva em vez de um índice exclusivo?

  • Quais são as principais causas de deadlocks e podem ser evitadas?

  • Como determinar se um Índice é necessário ou necessário

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve