Gatilho de auditoria de tabela do SQL Server
Eu tenho duas mesasCustomers
eAuditTable
. Quando eu modifico oCustomers
tabela, preciso inserir um novo registro no diretórioAuditTable
:
CREATE TABLE [dbo].[AuditTable]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[StateBefore] [nvarchar](max) NULL,
[StateAfter] [nvarchar](max) NULL
)
Eu preciso colocar uma representação XML deCustomer
estado emStateBefore
eStateAfter
, antes e depois da atualização.
oCustomer
tabela é:
CREATE TABLE [dbo].[Customer]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](256) NOT NULL,
[Email] [nvarchar](max) NOT NULL,
[IsDeleted] [bit] NULL,
[CreatedUtc] [datetime] NOT NULL,
[UpdatedUtc] [datetime] NULL,
[Version] [timestamp] NOT NULL,
CONSTRAINT [PK_dbo.Customer]
PRIMARY KEY CLUSTERED ([Id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON)
)
GO
ALTER TABLE [dbo].[Customer]
ADD DEFAULT (getutcdate()) FOR [CreatedUtc]
GO
Eu encontrei o caminho de como obter uma representação xml de linhas:
SELECT
[State] = (SELECT *
FROM dbo.Customer [Customer]
WHERE [Customer].Id = cust.Id
FOR XML AUTO
)
FROM
dbo.Customer cust
É apenas por exemplo. Então, no meu gatilho, preciso criar a representação xml das linhas dedeleted
einserted
mesas.
Aqui está o gatilho:
ALTER TRIGGER [dbo].[UpdateCustomerTrigger]
ON [dbo].[Customer]
FOR UPDATE
AS
BEGIN
UPDATE Customer
SET UpdatedUtc = GETDATE()
FROM INSERTED
WHERE inserted.id = Customer.Id
-- here I need to insert new records into AuditTable
END
Então, como posso juntar duas representações dedeleted
einserted
tabelas para inseri-las corretamente noAuditTable
? Obrigado.