Liberar toda a memória do servidor


Todos sabemos que o SQL é um consumidor de memória frenético, quanto mais memória disponível mais memória ele vai reservar para ele.

O que é um desenho “by default”, ele sempre fará isso afinal de contas ele precisa alocar as páginas de dados do seu banco em algum lugar.

Para resolver todos os seus problemas, existe uma forma de liberar toda a memória disponível de uma só vez do seu servidor e não é parando o serviço do SQL.

Para isso, você vai precisar o Visual Studio instalado, vamos criar um novo projeto dele…

Importante! Abra o Visual Studio como administrador !

Novo projeto de linha de comando

Escreva o nome que quiser para o app

Copie e cole o código abaixo no projeto:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

public class CriticalProcess
{
    [DllImport("ntdll.dll", SetLastError = true)]
    private static extern int NtSetInformationProcess(IntPtr hProcess, int processInformationClass, ref int processInformation, int processInformationLength);

    static void Main(string[] args)
    {
        int isCritical = 1;  // queremos que ele seja um processo crítico
        int BreakOnTermination = 0x1D;  // valor para BreakOnTermination (flag)

        Process.EnterDebugMode();  //acquire Debug Privileges

        // configurando o BreakOnTermination = 1 para o processo ativo
        NtSetInformationProcess(Process.GetCurrentProcess().Handle, BreakOnTermination, ref isCritical, sizeof(int));
    }
}

Se tudo ocorrer como esperado, dependendo da quantidade de memória do seu servidor isso pode demorar de alguns segundos a algumas horas.

Por mais que tenhamos criado uma aplicação de linha de comando a primeira parte do processo é bem gráfica e todos já tiveram o grande prazer de conhecer:

Ele vai gerar um DUMP de toda a memória para o arquivo de paginação e depois que a maquina reiniciar ele vai copiar esse arquivo de paginação para um arquivo chamado memory.dump

É só isso,,, execução e queda,,,

Agora falando sério: NUNCA !!!! JAMAIS !!!!! Simplesmente pegue o código de qualquer coisa que você encontra na internet e saia executando sem antes entender o que ele faz.

Esse exemplo é bem ridículo, mas imagina um script que você leu o por alto achando que vai resolver todos os seus problemas de backup, ou de fragmentação de índice e descobre que no meio tem um sp_msforeach_table com um sp_msforeach_db que trunca as tabelas, ou pior, alguém cria uma chave de criptografia e habilita TDE nas suas bases e depois força a remoção da chave,,,, a culpa é tão e somente sua! Você é o DBA é sua responsabilidade preservar os dados.

Tenha discernimento com o que você copia da internet e de onde copia essas informações.

SEMPRE LEIA e NUNCA EXECUTE DIRETAMENTE EM PRODUÇÃO !!!

Bah! – SQLSaturday #744 – Caxias do Sul Tchê !


Bah! Tchê! Vamos ver se eles realmente fazem um churrasco melhor que o paulista ou é só intriga da oposição.

No dia 23/06/2018 Haverá um novo evento do SQL Saturday, desta vez em Caxias do Sul/RS.

É com um prazer inenarrável em estar presente para mais um evento da comunidade e ainda mais como palestrante.

Só tem uma coisa mais legal que a minha palestra,,, o café,,, esqueça as outras, mantenha o foco,,,

Vamos conversar sobre formas “erradas” de como fazer as coisas no SQL Server.

SQL Server no Linux


Todos já devem estar sabendo dessa “novidade”

O link para o blog: https://blogs.microsoft.com/blog/2016/03/07/announcing-sql-server-on-linux

Se você quiser se cadastrar para “testar” o preview o link é: https://www.microsoft.com/en-us/server-cloud/sql-server-on-linux.aspx

Honestamente não sei se isso vai ser bom ou ruim,,, vejo muitas aplicações interessantes, mas também vejo muita dor de cabeça pela frente…

pode ser que eles usem isso para acabar com a versão Enterprise, forçando as empresas a usarem a nuvem caso queiram HA ou features avançadas? ou é uma forma de baratear o produto já que “em teoria” existem versões gratuitas de Linux? ainda mais pensando que ele vai ser distribuído por Docker,,,

Bom,,, de qualquer forma, mais uma coisa para relembrar,,, como faz tempo que não trabalho com linux… 😦

SQL Saturday #469 – Brasilia


E aí pessoal !!!

O conteúdo da palesta sobre backup parcial e restauração parcial e online está disponível.

O Slide está disponível para download ou visualização abaixo

O link para o download dos scripts e da apresentação está aqui.

Quero, novamente, agradecer pela oportunidade de ter palestrado no evento e agradecer a todos que tiveram paciência de assistir minha palestra.

O link para o acesso a agenda do evento é:

https://www.sqlsaturday.com/469/schedule.aspx

A ideia é a evolução contínua, gostaria que vocês avaliassem como foi a apresentação:

Event Notification para kill


i-see-dead-people-you-must-be-new-hereAlgum tempo atras fiz um post sobre Event Notification para monitorar DeadLock o que funciona muito bem,,,

Com um pouco de modificação o mesmo código pode ser utilizado para muitas outras coisas,,, por exemplo: limitar acesso a uma instância bloqueando a conexão do usuário…

Aí você pensa: “posso fazer isso por trigger, por que fazer diferente?”

Eu respondo,,, se você trabalha em ambientes com alto volume de conexões, ou ambientes que as vezes sofrem com falta de recursos como cpu ou memória sabe que a trigger pode ser uma pedra no sapato,,, ao invés de respeitar o filtro e impedir apenas algumas conexões ela bloqueia tudo e todos…

Já com o Event Notification é o contrário,,, no pior cenário ele só para de funcionar…

Os dois pontos que vejo como mais complicados são:

  • Não é possível personalizar uma mensagem para o usuário que sofreu o kill
  • Dependendo do que você fizer, ele pode começar a encher o errorlog com mensagens de kill

com o código abaixo consegui chegar a 20.000 tentativas de conexão simultâneas e nenhuma conseguiu conectar,,,


--apenas para constatar quais tipos de eventos podemos tratar... o que queremos eh o audit_login
select * from sys.event_notification_event_types with (nolock)
where type_name like '%login%'
use master
go

alter database BASE_DE_ADMINISTRACAO_DO_DBA set enable_broker with rollback immediate
go

alter database BASE_DE_ADMINISTRACAO_DO_DBA set TRUSTWORTHY on
go

use BASE_DE_ADMINISTRACAO_DO_DBA
go

CREATE QUEUE [Login_Killer_Queue]
GO

CREATE SERVICE [Login_Killer_Service]
AUTHORIZATION [dbo]
ON QUEUE [dbo].[Login_Killer_QUEUE]
([http://schemas.microsoft.com/SQL/Notifications/PostEventNotification])
GO
CREATE ROUTE Login_Killer_Route
WITH SERVICE_NAME = 'Login_Killer_Service',
ADDRESS = 'LOCAL';
GO
DECLARE @AuditServiceBrokerGuid [uniqueidentifier]
,@SQL [varchar](max);

-- Pega o service broker guid da base de dados
SELECT @AuditServiceBrokerGuid = [service_broker_guid]
FROM [master].[sys].[databases]
WHERE [name] = 'ADM_BDADOS'

-- Cria e executa o SQL dinamico para criar o objeto do evento de notificacao
SET @SQL = 'IF EXISTS (SELECT * FROM sys.server_event_notifications
WHERE name = ''Login_Killer_Notification'')

DROP EVENT NOTIFICATION Login_Killer_EventNotification ON SERVER

CREATE EVENT NOTIFICATION Login_Killer_EventNotification
ON SERVER
WITH fan_in
FOR AUDIT_LOGIN
TO SERVICE ''Login_Killer_Service'', '''
+ CAST(@AuditServiceBrokerGuid AS [varchar](50)) + ''';'
EXEC (@SQL)
GO
SELECT * FROM [sys].[server_event_notifications]

select * from sys.server_event_session_actions with (nolock)
CREATE TABLE [dbo].[DBA_FailedConnectionTracker](
[host_name] [varchar](128) NOT NULL,
[login_name] [varchar](128) NOT NULL,
[spidu] int,
[FailedLoginData] XML
) ;

CREATE PROCEDURE dbo.spc_DBA_FailedConnectionTracker
AS
BEGIN
SET NOCOUNT ON;
-- looping infinito
WHILE (1 = 1)
BEGIN
DECLARE @messageBody VARBINARY(MAX);
DECLARE @messageTypeName NVARCHAR(256);
WAITFOR (
RECEIVE TOP(1)
@messageTypeName = message_type_name,
@messageBody = message_body
FROM [Login_Killer_Queue]
), TIMEOUT 500
-- se nao houver mensagens saia
IF @@ROWCOUNT = 0
BEGIN
BREAK ;
END ;
-- se o tipo da mensagem for um EventNotification para a fila atual
IF (@messageTypeName = 'http://schemas.microsoft.com/SQL/Notifications/EventNotification')
BEGIN
DECLARE @XML XML,
@host_name varchar(128) ,
@login_name varchar(128) ,
@SPID varchar(5);

SELECT @XML=CONVERT(XML,@messageBody)
,@host_name = ''
,@login_name = ''
,@SPID ='';

-- Pega o SPID e as informacoes de login
SELECT @SPID = @XML.value('(/EVENT_INSTANCE/SPID)[1]', 'varchar(5)')
, @host_name = @XML.value('(/EVENT_INSTANCE/HostName)[1]', 'NVARCHAR(128)')
, @login_name = @XML.value('(/EVENT_INSTANCE/LoginName)[1]', 'NVARCHAR(128)')
;

DECLARE @kill varchar(8000) = '';
--Caso o hostname e o login entrem no criterio abaixo
if ((@host_name like 'SPO%') and (@login_name like '%_user'))
SELECT @kill = @kill + 'kill ' + @SPID + ';'
EXEC(@kill);

--/* esta parte pode ser comentada para não gerar "log" do kill
if ((@host_name like 'SPO%') and (@login_name like '%_user'))
INSERT INTO [dbo].[DBA_FailedConnectionTracker]
([host_name], [login_name], FailedLoginData,spidu)
values ( @host_name, @login_name,@XML,@SPID);
--*/
END;
END;
END;
--inicia a matanca

ALTER QUEUE [dbo].[Login_Killer_Queue]
WITH STATUS = on
,ACTIVATION (PROCEDURE_NAME = [spc_DBA_FailedConnectionTracker]
,STATUS = ON
,MAX_QUEUE_READERS = 1
,EXECUTE AS OWNER)
GO

MSDB e os Pacotes de SSIS


Esse código mostra o tamanho ocupado por cada pacote de SSIS carregado dentro do MSDB.

Algumas vezes o MSDB começa a ganhar proporções ocupadas que apenas a limpeza de rotina não dá conta e o pessoal esquece que os pacotes também ocupam espaço…


with ChildFolders
as
(
select PARENT.parentfolderid, PARENT.folderid, PARENT.foldername,
cast('' as sysname) as RootFolder,
cast(PARENT.foldername as varchar(max)) as FullPath,
0 as Lvl
from msdb.dbo.sysssispackagefolders PARENT
where PARENT.parentfolderid is null
UNION ALL
select CHILD.parentfolderid, CHILD.folderid, CHILD.foldername,
case ChildFolders.Lvl
when 0 then CHILD.foldername
else ChildFolders.RootFolder
end as RootFolder,
cast(ChildFolders.FullPath + '/' + CHILD.foldername as varchar(max))
as FullPath,
ChildFolders.Lvl + 1 as Lvl
from msdb.dbo.sysssispackagefolders CHILD
inner join ChildFolders on ChildFolders.folderid = CHILD.parentfolderid
)
select F.RootFolder, F.FullPath, P.name as PackageName,
P.description as PackageDescription, P.packageformat, P.packagetype,
P.vermajor, P.verminor, P.verbuild, P.vercomments,
cast(cast(P.packagedata as varbinary(max)) as xml) as PackageData,datalength(P.packagedata)/1024 AS SpaeceusedKB
from ChildFolders F
inner join msdb.dbo.sysssispackages P on P.folderid = F.folderid
order by F.FullPath asc, P.name asc;

Event Notification para monitorar DeadLock


A algumas semanas tivemos a necessidade de substituir a forma que usávamos para monitorar Dead Lock por alguma coisa mais usual…

Antes o Dead Lock era gravado no errorlog e depois encaminhado por email para o time,,, isso não é usual já que fica colocando muita informação desnecessária no errorlog e depois de alguns restarts perde-se algum histórico…

Com isso, cheguei a conclusão,,, vamos usar o event notification….

A vantagem é ser muito menos intrusivo que uma trigger e bem mais fácil de trabalhar que o System_Health…

Qual a ideia:

  1. O Event Notification vai enviar um email para cada vez que o evento de DeadLock acontecer, neste email vai conter informação da base que sofreu o DeadLock, horário e o DeadLock Graphic.
  2. Vai gravar em uma tabela na base de administração do DBA informações como: data e hora, base, XML com o evento.

use master
go

/*você já deve ter uma base de administração, caso não tenha, crie uma e troque o nome*/

alter database BASE_DE_ADMINISTRACAO_DO_DBA set enable_broker with rollback immediate
go

alter database BASE_DE_ADMINISTRACAO_DO_DBA set TRUSTWORTHY on
go

use BASE_DE_ADMINISTRACAO_DO_DBA
go

/**criando a tabela de controle/

create TABLE [dbo].[SQLDeadlockEvents](
[EventRowID] [bigint] primary key IDENTITY(1,1) NOT NULL,
[EventType] [nvarchar](128) NOT NULL,
[AlertTime] [datetime] NULL,
[DeadlockGraph] [xml] NULL,
[DatabaseName] [sysname] null,
[AuditDate] [smalldatetime]
) ON [FG_Data_01]
with (data_compression = PAGE) --neste caso tenho EE se você usar SE comente esta linha
GO

/**Criando a fila do Broker/

CREATE QUEUE [DeadlockGraphQueue]
GO

/*Criando o serviço para a fila do Broker*/

CREATE SERVICE [DeadlockEventsService]
AUTHORIZATION [dbo]
ON QUEUE [dbo].[DeadLockGraphQueue]
([http://schemas.microsoft.com/SQL/Notifications/PostEventNotification])
GO

/*criando rota*/

CREATE ROUTE DeadlockGraphRoute
WITH SERVICE_NAME = 'DeadlockEventsService',
ADDRESS = 'LOCAL';
GO

/* Para ficar mais fácil ele vai criar o event notification com os dados dinamicamente, se não, eu teria que explicar que o guid altera, onde tem que pegar essa informação,,, era mais SQL para uma coisa que pode ser feita de forma dinâmica */

DECLARE @AuditServiceBrokerGuid [uniqueidentifier]
,@SQL [varchar](max);

-- broker guid do CaptureDeadlockGraph
SELECT @AuditServiceBrokerGuid = [service_broker_guid]
FROM [master].[sys].[databases]
WHERE [name] = 'BASE_DE_ADMINISTRACAO_DO_DBA'

SET @SQL = 'IF EXISTS (SELECT * FROM sys.server_event_notifications
WHERE name = ''DeadlockGraphEventNotification'')

DROP EVENT NOTIFICATION DeadlockGraphEventNotification ON SERVER

CREATE EVENT NOTIFICATION DeadlockGraphEventNotification
ON SERVER --aqui é o detalhe legal... servidor e não database
WITH fan_in
FOR DEADLOCK_GRAPH
TO SERVICE ''DeadlockEventsService'', '''
+ CAST(@AuditServiceBrokerGuid AS [varchar](50)) + ''';'
EXEC (@SQL)
GO

/*Para confirmar que foi criado,,, lembra que é nível servidor,,, por isso a consulta no [sys].[server_event_notifications] */

SELECT * FROM [sys].[server_event_notifications]
WHERE [name] = 'DeadlockGraphEventNotification';
GO

/* onde a mágica acontece.... */
create PROC [dbo].[usp_sCaptureDeadlockGraph]
AS BEGIN

SET NOCOUNT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON

DECLARE @SQLProcedureName [varchar](64)
SET @SQLProcedureName = 'usp_sCaptureDeadlockGraph'

BEGIN TRY

DECLARE @message_body [xml]
, @EventTime [datetime]
, @EventType [varchar](128)
, @message_type_name [nvarchar](256)
, @dialog [uniqueidentifier]

-- Endless loop
WHILE (1 = 1)
BEGIN
BEGIN TRANSACTION ;

-- Receive the next available message
WAITFOR (RECEIVE TOP(1)
@message_type_name = [message_type_name],
@message_body = [message_body],
@dialog = [conversation_handle]
FROM [dbo].[DeadlockGraphQueue]), TIMEOUT 2000

-- Rollback and exit if no messages were found
IF (@@ROWCOUNT = 0)
BEGIN
ROLLBACK TRANSACTION;
BREAK;
END;

-- End conversation of end dialog message
IF (@message_type_name = 'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog')
BEGIN
PRINT 'End Dialog received for dialog # ' + CAST(@dialog as [nvarchar](40));
END CONVERSATION @dialog;
END;

ELSE
BEGIN

SET @EventTime = CAST(CAST(@message_body.query('/EVENT_INSTANCE/PostTime/text()') AS [nvarchar](max)) AS [datetime])
SET @EventType = CAST(@message_body.query('/EVENT_INSTANCE/EventType/text()') AS [nvarchar](128))

INSERT INTO [dbo].[SQLDeadlockEvents] ([EventType], [AlertTime], [DeadlockGraph])
VALUES (@EventType, @EventTime, @message_body)
END

COMMIT TRANSACTION

DECLARE @MailSubject [nvarchar](256)
,@MailBody [nvarchar](max)
,@SQLQuery [nvarchar](max)
,@AttachedFileName [nvarchar](256)
,@EventDateTime [datetime]
,@EventID [int]
,@Counter [int]
,@dbname [sysname]

IF EXISTS (SELECT * FROM [tempdb].[dbo].[sysobjects]
WHERE name = '##ListDeadlocks' AND type in (N'U'))
DROP TABLE ##ListDeadlocks

CREATE TABLE ##ListDeadlocks
([EventRowID] [int]
,[AlertTime] [datetime]
,[DeadlockGraph] [xml]
,[DeadlockXml] [xml])

INSERT INTO ##ListDeadlocks
([EventRowID]
,[AlertTime]
,[DeadlockGraph]
,[DeadlockXml])
SELECT [EventRowID]
,[AlertTime]
,[DeadlockGraph].query('./EVENT_INSTANCE/TextData/deadlock-list')
,DeadlockGraph FROM [dbo].[SQLDeadlockEvents]
WHERE [EventRowID] = @@IDENTITY

select @dbname = db_name(DeadlockGraph.value( '(/deadlock-list//@dbid)[1]', 'int' ))
--db_name(DeadlockGraph.value( '(/EVENT_INSTANCE/TextData/deadlock-list//@dbid)[1]', 'int' ) )
FROM ##ListDeadlocks
--where [EventRowID] = SCOPE_IDENTITY()

update [dbo].[SQLDeadlockEvents]
set [DatabaseName] = @dbname
where [EventRowID] = (select [EventRowID] FROM ##ListDeadlocks )

SELECT @Counter = MIN(EventRowID)
FROM ##ListDeadlocks

WHILE @Counter IS NOT NULL
BEGIN

SELECT @EventDateTime = [AlertTime]
,@EventID = [EventRowID]
FROM ##ListDeadlocks
WHERE [EventRowID] = @Counter

SELECT @MailSubject = 'Um deadlock ocorreu em ' + cast(@dbname as [varchar](256)) --+' servidor: '
--+ CONVERT([varchar](128), SERVERPROPERTY('ServerName'))
,@MailBody = 'Deadlock EventRowID: ' + CAST(@EventID AS [varchar](12))
+ char(13) + char(13) + 'O deadlock ocorreu as '
+ CONVERT([varchar](50), @EventDateTime, 120)
+ ' no Servidor: ' + CONVERT([varchar](128), SERVERPROPERTY('ServerName'))+'.'+char(13) + char(13) + 'Verifique o anexo xdl-file para mais detalhes.'
+ char(13) + char(13) +'Para mais informações ou eventos anteriores consulte: SELECT * FROM BASE_DE_ADMINISTRACAO_DO_DBA.dbo.SQLDeadlockEvents WITH (NOLOCK)'
,@SQLQuery = 'SET NOCOUNT ON; SELECT [DeadlockGraph] FROM [##ListDeadlocks] WITH (READUNCOMMITTED) WHERE EventRowID = '
+ CAST(@EventID AS [varchar](10))
,@AttachedFileName = CONVERT([varchar](128), SERVERPROPERTY('ServerName')) + '_' + CAST(@EventID AS [varchar](12)) + '.xdl'

EXEC msdb.dbo.sp_send_dbmail
@recipients = 'email@dominio.com.br' -- troque o email aqui
,@subject = @MailSubject
,@body = @MailBody
,@query = @SQLQuery
,@attach_query_result_as_file = 1 ,@query_attachment_filename = @AttachedFileName -- http://support.microsoft.com/kb/924345
,@query_result_header = 0
,@query_result_width = 32767
,@query_no_truncate = 1

DELETE FROM ##ListDeadlocks
WHERE EventRowID = @Counter

SELECT @Counter = MIN(EventRowID)
FROM ##ListDeadlocks
end
END --End of loop

END TRY

BEGIN CATCH

SELECT ERROR_NUMBER()
,ERROR_SEVERITY()
,ERROR_STATE()
,ISNULL(ERROR_PROCEDURE(), @SQLProcedureName)
,ERROR_LINE()
,ERROR_MESSAGE()

END CATCH

END
GO

/*inicia a fila para começar a capturar os DeadLocks*/
ALTER QUEUE [dbo].[DeadlockGraphQueue]
WITH STATUS = ON
,ACTIVATION (PROCEDURE_NAME = [usp_sCaptureDeadlockGraph]
,STATUS = ON
,MAX_QUEUE_READERS = 1
,EXECUTE AS OWNER)
GO

SQL Saturday #325 – São Paulo


E aí pessoal !!!

O conteúdo da palesta sobre backup parcial e restauração parcial e online está disponível.

O Slide está disponível para download ou visualização abaixo

O link para o download dos scripts e da apresentação está aqui.

Quero, novamente, agradecer pela oportunidade de ter palestrado no evento e agradecer a todos que tiveram paciência de assistir minha palestra.

O link para o acesso a agenda do evento é:

https://www.sqlsaturday.com/325/schedule.aspx

T-SQL Tuesday #57 – SQL Family and community


Para este mês o anfitrião do T-SQL Tuesday #57 é o Sr. Jeffery Verheul  (B|T)TSQL2sDay

Quando começamos como DBA´s, começamos lendo alguns livros, vendo alguns materiais na internet, participando de alguns treinamentos, etc… No começo acaba sendo bem assim,,, simples,,,

Aí você se depara com algum problema um pouco mais complicado,,, ou precisa fazer uma feature mais específica funcionar,,, e começa a perceber que existem mais pessoas mundo a fora que também mexem com essa coisa de SQL…

Ai descobre os BLOG´s,  fóruns de discussão, a hash #SQLHelp e vê que existem não mais,,, mas muito mais pessoas interessadas nessa coisinha chamada SQL… que o mundo não é só você com seu banquinho, mas com uma infinidade de pessoas precisando de ajuda e muitas outras dispostas a ajudar…

Quando você achou que já sabia de tudo que podia existir no SQL sempre vem alguém com mais e mais informação ou melhor forma ou solução para coisas que talvez você nem tivesse ideia que poderia acontecer…

Quantas vezes você não passou a noite em claro tentando resolver problemas e depois de colocar a pergunta no Twitter com a hashtag #SQLHelp teve a resposta em menos de 5 min? vinda de um cara que está provavelmente na Nova Zelândia que uma vez já passou por esse problema e fez um post em um blog  qualquer com a solução?

Após um tempo você percebe que existem várias fomas de interação, Ex.:

  • SQL Saturday – palestras presenciais gratuitas,
  • 24h de SQL – 24 horas de palestras online gratuitas
  • WebCasts – 1h30 sobre um assunto específico
  • #SQLHelp – ajuda
  • SQLPASS – Principal evento presencial (pago) da comunidade, só tem feras…
  • Fórum – a forma mais básica de P/R
  • Sites e mais sites… – olha você aqui lendo no meu site… 😀

E o melhor de tudo, tirando o SQLPASS e o twitter, tudo em português! Não tem nem como reclamar…

Quer começar a fazer parte? acesse o SQLPass faça um cadastro e veja as comunidades que existem na sua região… é de graça…

Isso é comunidade, pessoas ajudando pessoas. Não para massagear egos, mas pelo grande prazer em criar um lugar melhor, fazer as coisas melhores.

PS: uma coisa muito importante: Seja educado e agradeça! Se alguém gastou tempo para te ajudar a resolver algum problema ou para te dar um rumo para alguma coisa o mínimo da sua parte é agradecer.

Contar VLF


Esse script é bem simples, ele vai acessar todas as bases da instância e vai contar quantos VLF´s existem em cada base.
Nada muito complexo.
Qual a importância disso? Muitos VLF´s podem acarretar em um restore muito lento, ou uma inicialização da base muito demorada.
Isso acontece, em muitos casos, por crescimento desordenado do transaction log (crescimento em porcentagem, ou em tamanhos pequenos).
Podemos colocar da seguinte forma: Falta de planejamento e atenção.
Quer saber mais sobre VLF? esse vídeo é bem legal.
Existe alguma forma de corrigir isso? Claro… Não é bonito…
Vamos fazer um quiz, coloquem um comentário com a maior quantidade de VLF´s que vocês tem no ambiente…


CREATE TABLE #temp (
 RecoveryUnitID VARCHAR(255) --essa coluna só existe a partir do 2012, comente esta linha se for executar do 2008r2 para traz
 , FileID VARCHAR(255)
 , FileSize VARCHAR(255)
 , StartOffset VARCHAR(255)
 , FSeqNo VARCHAR(255)
 , [Status] VARCHAR(255)
 , Parity VARCHAR(255)
 , CreateLSN VARCHAR(255)
 )

CREATE TABLE #DBCCResults (
 ServerName VARCHAR(255)
 , DBName VARCHAR(255)
 , VLF bigint
 )

EXEC master.dbo.sp_MSforeachdb
 @command1 = 'USE ? INSERT INTO #temp EXECUTE (''DBCC LOGINFO'')'
 , @command2 = 'INSERT INTO #DBCCResults SELECT @@SERVERNAME, ''?'', count(1) FROM #temp'
 , @command3 = 'TRUNCATE TABLE #temp'

 SELECT DISTINCT
 ServerName
 , DBName
 , VLF
 FROM #DBCCResults
 ORDER BY 3 DESC

 DROP TABLE #temp, #DBCCResults;

Recuperar DML através do Transaction Log


Todos sabem que quando é feita uma operação no banco muita coisa passa pelo Transaction Log. Pode ser de minimamente logado ou até quase absolutamente tudo e todo mundo sabe que é possível restaurar tudo do que foi feito através dos arquivos de backup.

O script abaixo é o tipo de script que vale muito ser guardado com todo o carinho naquele pendrive cheio de outros scripts… Ele lê o transaction log e gera as operações para reverter alguma modificação na tabela que está sendo pesquisada.

Ok, eu sei que existem aplicações que fazem isso, mas elas são pagas e dependendo do cenário você não pode instalar uma aplicação dessas em um servidor.

Também existe a opção de recover do banco e voltar o transaction até um momento antes daquela operação mas pode ser que seu banco tenha alguns TB´s ou você não possa simplesmente parar toda empresa por causa de alguns registros e comprometer todas as outras operações de outras partes dos sistemas.

Antes de mais nada quer entender como o script funciona? Leia este post do Paul Randal (b| t) você vai entender como funciona o fn_dblog e o fn_dump_dblog

Agora o script…

Originalmente o script está localizado aqui.

Ele possui direitos de cópia livres para modificação/publicação/etc.

/******
(c) Walk the Way, 2014 (see accompanying license)
To use this:
1) SQL Server Management Studio must be "Run as administrator" (or using an admin account)
2) The SQL login User must have SQL sysadmin Server Role
For running DBCC PAGE: it appears that the SQL User must have SQL sysadmin Server Role
For sys.fn_dblog: the SQL User must have SELECT permission for "master" in System Databases
For SQL 2008 uncomment line 1150 (DATE not suppported in SQL 2005)

The WTW Open License

Copyright (c) 2014 Walk the Way; all rights reserved, except as follows:

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software as follows: the unrestricted right to use, copy, modify, merge,
publish, distribute, sublicense, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

modo de usar:

Recover_Modified_Data_Proc 'Nome_Da_Base', 'dbo.Tabela'

Recover_Modified_Data_Proc 'Nome_Da_Base', 'dbo.Tabela', '2014/07/16', '2014/07/18' --com periodo

******/
IF EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[Recover_Modified_Data_Proc]')
AND TYPE IN ( N'FN', N'IF', N'TF', N'FS', N'FT', N'P' ))
SET NOEXEC ON

--> Based on the work of Muhammad Imran generously published at:
--> http://raresql.com/2012/02/01/how-to-recover-modified-records-from-sql-server-part-1/
-->
--> Uncomment/Comment block below for testing/development
/****************************************
SET NOEXEC OFF
IF OBJECT_ID (N'[@ResultTable]', N'U') IS NOT NULL DROP TABLE [@ResultTable]
IF OBJECT_ID('tempdb..#T1') IS NOT NULL DROP TABLE #T1
IF OBJECT_ID('tempdb..#temp_Data') IS NOT NULL DROP TABLE #temp_Data
IF OBJECT_ID('tempdb..#CTE') IS NOT NULL DROP TABLE #CTE
IF OBJECT_ID('tempdb..#TransIdUpdateList') IS NOT NULL DROP TABLE #TransIdUpdateList
IF OBJECT_ID('tempdb..#TransIdDeleteList') IS NOT NULL DROP TABLE #TransIdDeleteList
IF OBJECT_ID('tempdb..#TransIdAllList') IS NOT NULL DROP TABLE #TransIdAllList
IF OBJECT_ID('tempdb..#AllocIdList') IS NOT NULL DROP TABLE #AllocIdList
IF OBJECT_ID('tempdb..#SysFnDblog') IS NOT NULL DROP TABLE #SysFnDblog
IF OBJECT_ID('tempdb..#DelRows') IS NOT NULL DROP TABLE #DelRows
DECLARE @Database_Name NVARCHAR(MAX)
DECLARE @SchemaName_n_TableName NVARCHAR(MAX)
DECLARE @Date_From DATETIME
DECLARE @Date_To DATETIME
SET @Database_Name = 'Test'
SET @SchemaName_n_TableName = 'Student'
SET @Date_From = '2014/05/22' --'1900/01/01'
SET @Date_To = '2099/01/01' --'9999/12/31'
print @Date_From
print @Date_To
****************************************/
--> Uncomment/Comment block below to create Stored Procedure
/****************************************/
IF OBJECT_ID('Recover_Modified_Data_Proc', 'P') IS NOT NULL
DROP PROC Recover_Modified_Data_Proc
GO
Create PROCEDURE Recover_Modified_Data_Proc
@Database_Name NVARCHAR(MAX),
@SchemaName_n_TableName NVARCHAR(MAX),
@Date_From DATETIME = '1900/01/01', --> Null equivalent
@Date_To DATETIME = '9999/12/31' --> largest date
AS

--> For SQL 2005; PIVOT requires compatibility_level = 90
IF ((SELECT [compatibility_level] from sys.databases where [name] = @Database_Name) < 90) BEGIN
RETURN -1
END
/****************************************/

DECLARE @Debug INT
SET @Debug = 0
DECLARE @parms NVARCHAR(1024)
DECLARE @Fileid INT
DECLARE @hex_pageid AS VARCHAR(MAX)
DECLARE @Pageid INT
DECLARE @Slotid INT
DECLARE @TransactionName VARCHAR(MAX)
DECLARE @CurrentLSN VARCHAR(MAX)
DECLARE @BeginTime DATETIME
DECLARE @RowLogContents0 VARBINARY(8000)
DECLARE @RowLogContents1 VARBINARY(8000)
DECLARE @RowLogContents2 VARBINARY(8000)
DECLARE @RowLogContents3 VARBINARY(8000)
DECLARE @RowLogContents3_Var VARCHAR(MAX)

DECLARE @RowLogContents4 VARBINARY(8000)
DECLARE @LogRecord VARBINARY(8000)
DECLARE @LogRecord_Var VARCHAR(MAX)

DECLARE @ConsolidatedPageID VARCHAR(MAX)
DECLARE @AllocUnitID BIGINT
DECLARE @TransactionID VARCHAR(MAX)
DECLARE @Operation VARCHAR(MAX)
DECLARE @DatabaseCollation VARCHAR(MAX)

--FOR @Operation ='LOP_MODIFY_COLUMNS'
DECLARE @RowLogData_Var VARCHAR(MAX)
DECLARE @RowLogData_Hex VARBINARY(MAX)

DECLARE @TotalFixedLengthData INT
DECLARE @FixedLength_Offset INT
DECLARE @VariableLength_Offset INT
DECLARE @VariableLength_Offset_Start INT
DECLARE @VariableLengthIncrease INT
DECLARE @FixedLengthIncrease INT
DECLARE @OldFixedLengthStartPosition INT
DECLARE @FixedLength_Loc INT
DECLARE @VariableLength_Loc INT
DECLARE @FixedOldValues VARBINARY(MAX)
DECLARE @FixedNewValues VARBINARY(MAX)
DECLARE @VariableOldValues VARBINARY(MAX)
DECLARE @VariableNewValues VARBINARY(MAX)

/* Pick The actual data
*/
DECLARE @temppagedata TABLE(
[RecordID] INT IDENTITY(1,1)
,[ParentObject] sysname
,[Object] sysname
,[Field] sysname
,[Value] sysname
)

DECLARE @pagedata TABLE(
[Page Index] int
,[DBCCid] int
,[ParentObject] sysname
,[Object] sysname
,[Field] sysname
,[Value] sysname
)

DECLARE @pageindex TABLE(
[PageIndexID] INT IDENTITY(1,1)
,[ConsolidatedPageID] VARCHAR(MAX)
,[Fileid] VARCHAR(MAX)
,[hex_pageid] VARCHAR(MAX)
,[Pageid] VARCHAR(MAX)
)

IF (@Debug > 2) BEGIN
--select * from sys.fn_dblog(NULL, NULL)
--> http://db4breakfast.blogspot.com/2013/03/fndblog-function-documentation.html
--> IMPORTANT: [databasename] > Properties > Options > Recovery Model: Full
--> http://msdn.microsoft.com/en-us/library/ms189275.aspx --> Recovery Models (SQL Server)
--> http://technet.microsoft.com/en-us/library/ms189272.aspx
--> ALTER DATABASE model SET RECOVERY FULL
--> Immediately after switching from the simple recovery model to the full recovery model or bulk-logged recovery model, take a full or differential database backup to start the log chain.
--> The switch to the full or bulk-logged recovery model takes effect only after the first data backup.
SELECT name, recovery_model_desc
FROM sys.databases
WHERE name = 'model' ;

select 'Log file usage'
SELECT name AS [File Name],
physical_name AS [Physical Name],
size/128.0 AS [Total Size in MB],
size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS int)/128.0 AS [Available Space In MB],
[growth], [file_id]
,B.cntr_value as "LogFullPct"
FROM sys.database_files A
INNER JOIN sys.dm_os_performance_counters B ON RTRIM(B.instance_name)+'_log' = A.name
WHERE type_desc = 'LOG'
AND B.counter_name LIKE 'Percent Log Used%'
AND B.instance_name not in ('_Total', 'mssqlsystemresource')
--SELECT instance_name as [Database],cntr_value as "LogFullPct"
-- FROM sys.dm_os_performance_counters A
-- WHERE counter_name LIKE 'Percent Log Used%'
-- AND instance_name not in ('_Total', 'mssqlsystemresource')
-- AND cntr_value > 0;
END
IF (@Debug > 3) BEGIN
select 'sys.fn_dblog(NULL, NULL)'
--> LSN = Log Sequence Number
select [Current LSN],[Operation],[Context],[TRANSACTION ID],[Transaction Name],[Previous LSN],[AllocUnitId],[AllocUnitName],[Begin Time]
,[RowLog Contents 0],[RowLog Contents 1],[RowLog Contents 2],[RowLog Contents 3],[RowLog Contents 4],SUSER_SNAME([Transaction SID]) AS [Transaction Account]
from sys.fn_dblog(NULL, NULL)
where [TRANSACTION ID] IN (SELECT DISTINCT [TRANSACTION ID] FROM sys.fn_dblog(NULL, NULL) WHERE [Transaction Name] IN ('UPDATE','DELETE','INSERT'))
order by [Current LSN]
--select * from sys.allocation_units
END

--> Get [TRANSACTION ID]s & [Transaction Name]s for INSERTs, DELETEs, UPDATEs in the time range
-- This includes: [Operation]s of ('LOP_MODIFY_ROW','LOP_MODIFY_COLUMNS','LOP_INSERT_ROWS','LOP_DELETE_ROWS')
/*Use this subquery to filter the date*/
SELECT DISTINCT [TRANSACTION ID],[Transaction Name],SUSER_SNAME([Transaction SID]) AS [Transaction Account]
INTO #TransIdAllList
FROM sys.fn_dblog(NULL, NULL)
WHERE [Context] IN ('LCX_NULL') AND [Operation] IN ('LOP_BEGIN_XACT')
AND [Transaction Name] IN ('UPDATE','INSERT','DELETE')
AND CONVERT(NVARCHAR(11),[Begin Time]) BETWEEN @Date_From AND @Date_To

--> Now remove all ('UPDATE','INSERT','DELETE')_transactions that are NOT ('LOP_MODIFY_ROW','LOP_MODIFY_COLUMNS','LOP_INSERT_ROWS','LOP_DELETE_ROWS')_transactions
DELETE FROM #TransIdAllList WHERE [TRANSACTION ID] IN
(SELECT DISTINCT [TRANSACTION ID]
--INTO #TransIdAllList
FROM sys.fn_dblog(NULL, NULL)
WHERE [TRANSACTION ID] IN (SELECT [TRANSACTION ID] FROM #TransIdAllList)
AND [Operation] NOT IN (NULL,'LOP_MODIFY_ROW','LOP_MODIFY_COLUMNS','LOP_INSERT_ROWS','LOP_DELETE_ROWS'))

--> Get [TRANSACTION ID]s for UPDATEs in time range; both 'LOP_MODIFY_ROW' & 'LOP_MODIFY_COLUMNS'
SELECT [TRANSACTION ID],[Transaction Name]
INTO #TransIdUpdateList
FROM #TransIdAllList
WHERE [Transaction Name] IN ('UPDATE')

--> Get [TRANSACTION ID]s for DELETEs in time range
-- WARNING: the @Date_To needs to include the DELETE for deleted UPDATEs
SELECT DISTINCT [TRANSACTION ID]
INTO #TransIdDeleteList
FROM #TransIdAllList
WHERE [Transaction Name] IN ('DELETE')

--> Get appropriate [Allocation_unit_id]s
SELECT [Allocation_unit_id]
INTO #AllocIdList
FROM sys.allocation_units allocunits
INNER JOIN sys.partitions partitions ON
(allocunits.type IN (1, 3) AND partitions.hobt_id = allocunits.container_id)
OR (allocunits.type = 2 AND partitions.partition_id = allocunits.container_id)
WHERE object_id=object_ID('' + @SchemaName_n_TableName + '')

--> Get the sys.fn_dblog record info for all transactions of concern
SELECT [Current LSN],[Operation],[Context],[PAGE ID],[AllocUnitId],[Slot ID],[TRANSACTION ID],[Transaction Name],[Begin Time],[RowLog Contents 0],[RowLog Contents 1],[RowLog Contents 2],[RowLog Contents 3],[RowLog Contents 4],[Log Record Length],[Log Record Fixed Length],[Log Record]
INTO #SysFnDblog
FROM sys.fn_dblog(NULL, NULL)
WHERE [TRANSACTION ID] IN (SELECT [TRANSACTION ID] FROM #TransIdAllList)
--select * from #SysFnDblog

--> Get record info for deleted rows for UPDATEs that may have been deleted
SELECT [PAGE ID],[AllocUnitId],[Slot ID],[TRANSACTION ID],MAX([RowLog Contents 0]) AS [RowLog Contents 0] --> removes NULLs
INTO #DelRows
FROM #SysFnDblog
WHERE [Operation] IN ('LOP_DELETE_ROWS')
AND [AllocUnitId] IN (SELECT * FROM #AllocIdList)
AND [TRANSACTION ID] IN (SELECT * FROM #TransIdDeleteList)
GROUP BY [PAGE ID],[AllocUnitId],[Slot ID],[TRANSACTION ID]

IF (@Debug > 1) BEGIN
SELECT '#TransIdAllList'
SELECT * FROM #TransIdAllList
SELECT '#TransIdUpdateList'
SELECT * FROM #TransIdUpdateList
SELECT '#TransIdDeleteList'
SELECT * FROM #TransIdDeleteList
SELECT '#AllocIdList'
SELECT * FROM #AllocIdList
SELECT '#SysFnDblog '
SELECT * FROM #SysFnDblog
print 'select * from #DelRows'
SELECT '#DelRows'
SELECT * FROM #DelRows
END

DECLARE @ModifiedRawData TABLE(
[ID] INT IDENTITY(1,1)
,[PAGE ID] VARCHAR(MAX)
,[Slot ID] INT
,[AllocUnitId] BIGINT
,[Datum] VARCHAR(20)
,[TRANSACTION ID] VARCHAR(MAX)
,[Transaction Name] VARCHAR(MAX)
,[Current LSN] VARCHAR(MAX)
,[EntryID] INT DEFAULT -1
,[PrevEntry] INT DEFAULT -1
,[NextEntry] INT DEFAULT -1
,[ChainLevel] INT DEFAULT -1
,[Process] INT DEFAULT -1
,[Begin Time] DATETIME
,[RowLog Contents 0_var] VARCHAR(MAX)
,[RowLog Contents 0] VARBINARY(8000)
,[Slot Info] VARCHAR(MAX)
)

--> Get UPDATEd records information
INSERT INTO @ModifiedRawData ([PAGE ID],[Slot ID],[AllocUnitId],[Datum],[TRANSACTION ID],[Transaction Name],[Current LSN],[Begin Time],[RowLog Contents 0_var])
SELECT A.[PAGE ID],A.[Slot ID],A.[AllocUnitId],'Reference' AS [Datum],A.[TRANSACTION ID]
,(SELECT [Transaction Name] FROM #TransIdUpdateList WHERE [TRANSACTION ID] = A.[TRANSACTION ID]) AS [Transaction Name] --> always = 'UPDATE' here
,A.[Current LSN]
,(SELECT MAX([Begin Time]) FROM #SysFnDblog WHERE [TRANSACTION ID] = A.[TRANSACTION ID]) AS [Begin Time] --> eliminates NULL values
,NULL AS [Value] --> [RowLog Contents 0_var]
FROM #SysFnDblog A
WHERE A.[AllocUnitId] IN (SELECT * FROM #AllocIdList)
AND [Operation] IN ('LOP_MODIFY_ROW','LOP_MODIFY_COLUMNS')
AND [Context] IN ('LCX_HEAP','LCX_CLUSTERED')
AND [TRANSACTION ID] IN (SELECT [TRANSACTION ID] FROM #TransIdUpdateList)
GROUP BY A.[PAGE ID],A.[Slot ID],A.[AllocUnitId],[Begin Time],[Transaction ID],[Transaction Name],A.[Current LSN]
ORDER BY [Slot ID],[Current LSN] --> [Slot ID] is the record entry number
--SELECT * FROM @ModifiedRawData

--> Get the indexing information for DBCC PAGE
INSERT INTO @pageindex ([ConsolidatedPageID],[Fileid],[hex_pageid],[Pageid])
SELECT DISTINCT [PAGE ID],NULL,NULL,NULL FROM @ModifiedRawData
UPDATE @pageindex
SET [Fileid] = SUBSTRING([ConsolidatedPageID],0,CHARINDEX(':',[ConsolidatedPageID])) -- Seperate File ID from Page ID
, [hex_pageid] = '0x'+ SUBSTRING([ConsolidatedPageID],CHARINDEX(':',[ConsolidatedPageID])+1,LEN([ConsolidatedPageID])) -- Seperate the page ID
UPDATE @pageindex
SET [Pageid] = CONVERT(INT,CAST('' AS XML).value('xs:hexBinary(substring(sql:column("[hex_pageid]"),sql:column("t.pos")) )', 'varbinary(max)')) -- Convert Page ID from hex to integer
FROM (SELECT CASE SUBSTRING([hex_pageid], 1, 2) WHEN '0x' THEN 3 ELSE 0 END FROM @pageindex A WHERE A.[PageIndexID] = [PageIndexID]) AS t(pos)
--SELECT * FROM @pageindex

/*******************CURSOR START*********************/
--> Get DBCC PAGE data for each [ConsolidatedPageID]
DECLARE Page_Data_Cursor CURSOR FOR
SELECT [Fileid],[Pageid]
FROM @pageindex
ORDER BY [Fileid],[Pageid]
/****************************************/
OPEN Page_Data_Cursor

FETCH NEXT FROM Page_Data_Cursor INTO @Fileid,@Pageid
WHILE @@FETCH_STATUS = 0
BEGIN
DELETE @temppagedata
--> the next line requires cursor use due to augument requirements
INSERT INTO @temppagedata EXEC( 'DBCC PAGE(' + @DataBase_Name + ', ' + @Fileid + ', ' + @Pageid + ', 3) with tableresults,no_infomsgs;')
--> Concatenante all DBCC PAGE pages into one file by [ConsolidatedPageID] using index [PageIndexID]
INSERT INTO @pagedata ([Page Index],[DBCCid],[ParentObject],[Object],[Field],[Value])
SELECT B.[PageIndexID],A.[RecordID],[ParentObject],[Object],[Field],[Value]
FROM @temppagedata A
JOIN @pageindex B ON B.[Pageid] = @Pageid AND B.[Fileid] = @Fileid
FETCH NEXT FROM Page_Data_Cursor INTO @Fileid,@Pageid
END

CLOSE Page_Data_Cursor
DEALLOCATE Page_Data_Cursor
/*******************CURSOR END*********************/

--> Add the DBCC PAGE information OR DELETEd info to the UPDATEd records information
-- DBCC PAGE indexing is independent of [AllocUnitId]
UPDATE @ModifiedRawData
SET
[RowLog Contents 0_var] =
COALESCE( --> look for DBCC PAGE record set
UPPER((SELECT REPLACE(STUFF(
(SELECT REPLACE(SUBSTRING([VALUE],CHARINDEX(':',[Value])+1,48),'†','')
FROM @pagedata C
WHERE B.[Page Index] = C.[Page Index] --> EQUIVALENT to [ConsolidatedPageID]
AND A.[Slot ID] = LTRIM(RTRIM(SUBSTRING(C.[ParentObject],5,3)))
AND [Object] LIKE '%Memory Dump%'
GROUP BY [Value] FOR XML PATH('')
),1,1,'') ,' ','')
)) --> next, look for deleted record
,UPPER(CAST('' AS XML).value('xs:hexBinary(sql:column("C.[RowLog Contents 0]") )', 'varchar(max)'))
,'ERROR: '+B.[ParentObject] --> Missing [Slot ID] in "DBCC PAGE", and no corresponding DELETE found
)
,[Slot Info] = COALESCE(B.[ParentObject],'Slot '+CONVERT(VARCHAR,C.[Slot ID])+' deleted')
FROM @ModifiedRawData A
INNER JOIN @pageindex D ON D.[ConsolidatedPageID] = A.[PAGE ID]
LEFT JOIN @pagedata B ON
B.[Page Index] = D.[PageIndexID]
AND A.[Slot ID] = LTRIM(RTRIM(SUBSTRING(B.[ParentObject],5,3)))
AND B.[Object] LIKE '%Memory Dump%'
LEFT JOIN #DelRows C ON
C.[PAGE ID]=[A].[PAGE ID]
AND C.[AllocUnitId] = A.[AllocUnitId]
AND C.[Slot ID] = A.[Slot ID]

--> Convert the old data which is in string format to hex format (required).
UPDATE @ModifiedRawData SET [RowLog Contents 0] = CAST('' AS XML).value('xs:hexBinary(substring(sql:column("[RowLog Contents 0_var]"), 0) )', 'varbinary(max)')
FROM @ModifiedRawData

IF (@Debug > 0) BEGIN
select '@pageindex'
select * from @pageindex
select '@DBCC PAGE'
select * from @temppagedata
select '@pagedata'
select * from @pagedata --ORDER BY [Page ID],[AllocUnitId],[Current LSN],[DBCCid]
print 'select * from @ModifiedRawData1'
select '@ModifiedRawData1'
select * from @ModifiedRawData
END

DECLARE @PreliminaryRawData TABLE(
[ID] INT IDENTITY(1,1)
,[PAGE ID] VARCHAR(MAX)
,[Slot ID] INT
,[AllocUnitId] BIGINT
,[Datum] VARCHAR(20)
,[TRANSACTION ID] VARCHAR(MAX)
,[Transaction Name] VARCHAR(MAX)
,[Current LSN] VARCHAR(MAX)
,[Begin Time] DATETIME
,[RowLog Contents 0] VARBINARY(8000)
,[RowLog Contents 1] VARBINARY(8000)
,[RowLog Contents 2] VARBINARY(8000)
,[RowLog Contents 3] VARBINARY(8000)
,[RowLog Contents 4] VARBINARY(8000)
,[Log Record] VARBINARY(8000)
,[Operation] VARCHAR(MAX)
,[RowLog Contents 0_var] VARCHAR(MAX)
,[RowLog Contents 1_var] VARCHAR(MAX)
)

---Now we have the modifed data plus its slot ID , page ID and allocunit as well.
--After that we need to get the old values before modfication, these data are in chunks.
INSERT INTO @PreliminaryRawData
SELECT [PAGE ID],[Slot ID],[AllocUnitId],'Restoration' AS [Datum],[TRANSACTION ID]
,(SELECT [Transaction Name] FROM #TransIdAllList WHERE [TRANSACTION ID] = A.[TRANSACTION ID]) AS [Transaction Name]
,[Current LSN]
,(SELECT MAX([Begin Time]) FROM #SysFnDblog WHERE [TRANSACTION ID] = A.[TRANSACTION ID]) AS [Begin Time] --> eliminates NULL values
,[RowLog Contents 0],[RowLog Contents 1],[RowLog Contents 2],[RowLog Contents 3],[RowLog Contents 4]
,SUBSTRING ([Log Record],[Log Record Fixed Length],([Log Record Length]+1)-([Log Record Fixed Length])) as [Log Record]
,[Operation]
,UPPER(CAST('' AS XML).value('xs:hexBinary(sql:column("[RowLog Contents 0]") )', 'varchar(max)')) AS [RowLog Contents 0_var] --> New, added for reference; integrated below
,UPPER(CAST('' AS XML).value('xs:hexBinary(sql:column("[RowLog Contents 1]") )', 'varchar(max)')) AS [RowLog Contents 1_var] --> New, added for reference; integrated below
FROM #SysFnDblog A
WHERE [AllocUnitId] IN (SELECT * FROM #AllocIdList)
AND [Operation] IN ('LOP_MODIFY_ROW','LOP_MODIFY_COLUMNS','LOP_INSERT_ROWS','LOP_DELETE_ROWS')
AND [Context] IN ('LCX_HEAP','LCX_CLUSTERED')
--AND [TRANSACTION ID] IN (SELECT [TRANSACTION ID] FROM #TransIdAllList) --> same filter for #SysFnDblog
ORDER BY [Slot ID],[Transaction ID] DESC
--SELECT * FROM @PreliminaryRawData
/*
If the [Operation] Type is 'LOP_MODIFY_ROW' then it is very simple to recover the modified data. The old data is in [RowLog Contents 0] Field and modified data is in [RowLog Contents 1] Field. Simply replace it with the modified data and get the old data.
If the [Operation] Type is 'LOP_INSERT_ROWS' or 'LOP_DELETE_ROWS' then it is very simple to recover the data. The old data is in [RowLog Contents 0] Field.
*/
INSERT INTO @ModifiedRawData ([PAGE ID],[Slot ID],[AllocUnitId],[Datum],[TRANSACTION ID],[Transaction Name],[Current LSN],[Begin Time],[RowLog Contents 0_var],[Slot Info])
SELECT A.[PAGE ID],A.[Slot ID],A.[AllocUnitId],'Restoration' AS [Datum],A.[TRANSACTION ID],A.[Transaction Name],A.[Current LSN],A.[Begin Time]
,CASE WHEN A.[Operation] IN ('LOP_INSERT_ROWS','LOP_DELETE_ROWS') THEN
(SELECT UPPER(CAST('' AS XML).value('xs:hexBinary(sql:column("A.[RowLog Contents 0]") )','varchar(max)'))) --> for INSERTs and/or DELETEs with no UPDATEs (@ModifiedRawData is empty when this update starts)
ELSE --> look for the UPDATE mate from the previous record pull
REPLACE(UPPER(B.[RowLog Contents 0_var]),UPPER(CAST('' AS XML).value('xs:hexBinary(sql:column("A.[RowLog Contents 1]") )','varchar(max)')),UPPER(CAST('' AS XML).value('xs:hexBinary(sql:column("A.[RowLog Contents 0]") )','varchar(max)')))
END AS [RowLog Contents 0_var]
,B.[Slot Info]
FROM @PreliminaryRawData A
LEFT JOIN @ModifiedRawData B ON B.[Current LSN]=A.[Current LSN]
WHERE A.[Operation] IN ('LOP_MODIFY_ROW','LOP_INSERT_ROWS','LOP_DELETE_ROWS')

-- Convert the old data which is in string format to hex format (required).
UPDATE @ModifiedRawData SET [RowLog Contents 0] = CAST('' AS XML).value('xs:hexBinary(substring(sql:column("[RowLog Contents 0_var]"), 0) )', 'varbinary(max)')
FROM @ModifiedRawData
WHERE [RowLog Contents 0] IS NULL

IF (@Debug > 0) BEGIN
select '@PreliminaryRawData'
select * from @PreliminaryRawData
print 'select * from @ModifiedRawData2_row_ops'
select '@ModifiedRawData2_row_ops'
select * from @ModifiedRawData
END
--> remove these records since their processing is complete
--DELETE FROM @PreliminaryRawData WHERE [Operation] IN ('LOP_MODIFY_ROW','LOP_INSERT_ROWS','LOP_DELETE_ROWS')
DELETE FROM @PreliminaryRawData WHERE [Operation] IN ('LOP_INSERT_ROWS','LOP_DELETE_ROWS')
IF (@Debug > 0) BEGIN
print 'select * from @PreliminaryRawData_remaining'
select '@PreliminaryRawData_remaining'
select * from @PreliminaryRawData
END

/*******************CURSOR START*********************/
---Now we have modifed data plus its slot ID , page ID and allocunit as well.
--After that we need to get the old values before modfication, these data are in chunks.
IF (@Debug = 0) BEGIN
DECLARE Page_Data_Cursor CURSOR FOR
SELECT [PAGE ID],[Slot ID],[AllocUnitId],[TRANSACTION ID],[Transaction Name],[Current LSN],[Begin Time],[RowLog Contents 0],[RowLog Contents 1],[RowLog Contents 2],[RowLog Contents 3],[RowLog Contents 4],[Log Record],[Operation]
FROM @PreliminaryRawData
WHERE [Operation] IN ('LOP_MODIFY_COLUMNS')
ORDER BY [Slot ID],[TRANSACTION ID] DESC
END
ELSE
BEGIN
DECLARE Page_Data_Cursor CURSOR FOR
SELECT [PAGE ID],[Slot ID],[AllocUnitId],[TRANSACTION ID],[Transaction Name],[Current LSN],[Begin Time],[RowLog Contents 0],[RowLog Contents 1],[RowLog Contents 2],[RowLog Contents 3],[RowLog Contents 4],[Log Record],[Operation]
FROM @PreliminaryRawData
ORDER BY [Slot ID],[TRANSACTION ID] DESC
END

/****************************************/

OPEN Page_Data_Cursor

FETCH NEXT FROM Page_Data_Cursor INTO @ConsolidatedPageID,@Slotid,@AllocUnitID,@TransactionID,@TransactionName,@CurrentLSN,@BeginTime,@RowLogContents0,@RowLogContents1,@RowLogContents2,@RowLogContents3,@RowLogContents4,@LogRecord,@Operation
WHILE @@FETCH_STATUS = 0
BEGIN
IF @Operation IN ('LOP_MODIFY_ROW','LOP_INSERT_ROWS','LOP_DELETE_ROWS')
BEGIN
-- To see the debug printout, comment out the "DELETE FROM @PreliminaryRawData..." line above
IF (@Debug > 1) BEGIN
PRINT 'ConsolidatedPageID = '+@ConsolidatedPageID
PRINT 'Slotid = '+CONVERT(nvarchar,@Slotid)
PRINT 'AllocUnitID = '+CONVERT(nvarchar,@AllocUnitID)
PRINT 'TransactionID = '+@TransactionID
PRINT 'BeginTime = '+CONVERT(nvarchar,@BeginTime,121)
PRINT 'TransactionName = '+@TransactionName
DECLARE @RowLogContents0_var VARCHAR(MAX)
DECLARE @RowLogContents1_var VARCHAR(MAX)
SET @RowLogContents0_var=(SELECT UPPER(CAST('' AS XML).value('xs:hexBinary(sql:variable("@RowLogContents0") )', 'varchar(max)')))
SET @RowLogContents1_var=(SELECT UPPER(CAST('' AS XML).value('xs:hexBinary(sql:variable("@RowLogContents1") )', 'varchar(max)')))
PRINT 'RowLogContents0 = '+@RowLogContents0_var
PRINT 'RowLogContents1 = '+@RowLogContents1_var
IF (@TransactionName='UPDATE') BEGIN
DECLARE @RowLogContents0_var1 VARCHAR(MAX)
DECLARE @RowLogContents0_var2 VARCHAR(MAX)
DECLARE @RowLogContents1_var0 VARCHAR(MAX)
DECLARE @RowLogContents0_var0 VARCHAR(MAX)
SET @RowLogContents0_var1=(SELECT [RowLog Contents 0_var]
FROM @ModifiedRawData
WHERE [Current LSN]=@CurrentLSN AND [Datum]='Reference')
SET @RowLogContents1_var0=(SELECT UPPER(CAST('' AS XML).value('xs:hexBinary(sql:variable("@RowLogContents1") )','varchar(max)'))
FROM @ModifiedRawData
WHERE [Current LSN]=@CurrentLSN AND [Datum]='Reference')
SET @RowLogContents0_var0=(SELECT UPPER(CAST('' AS XML).value('xs:hexBinary(sql:variable("@RowLogContents0") )','varchar(max)'))
FROM @ModifiedRawData
WHERE [Current LSN]=@CurrentLSN AND [Datum]='Reference')
SET @RowLogContents0_var2=(SELECT REPLACE(UPPER([RowLog Contents 0_var]),UPPER(CAST('' AS XML).value('xs:hexBinary(sql:variable("@RowLogContents1") )','varchar(max)')),UPPER(CAST('' AS XML).value('xs:hexBinary(sql:variable("@RowLogContents0") )','varchar(max)')))
FROM @ModifiedRawData
WHERE [Current LSN]=@CurrentLSN AND [Datum]='Reference')
PRINT 'RowLogContents0_var1 = '+@RowLogContents0_var1
PRINT 'RowLogContents1_var0 = '+@RowLogContents1_var0
PRINT 'RowLogContents0_var0 = '+@RowLogContents0_var0
PRINT 'RowLogContents0_var2 = '+@RowLogContents0_var2
PRINT 'RowLogContents0_var2a= '+REPLACE(@RowLogContents0_var1,@RowLogContents1_var0,@RowLogContents0_var0)
END
PRINT ''
--DECLARE @LSN VARCHAR(50)
--DECLARE @LSN0 VARCHAR(50)
--DECLARE @LSN1 VARCHAR(50)
--DECLARE @LSN2 VARCHAR(50)
--DECLARE @LSN_int1 INTEGER
--DECLARE @LSN_int2 INTEGER
--SET @LSN=CONVERT(VARCHAR,@CurrentLSN)
--SET @LSN_int1=CHARINDEX(':',@LSN,1)
--SET @LSN_int2=CHARINDEX(':',@LSN,@LSN_int1+1)
--SET @LSN0=SUBSTRING(@LSN,1,@LSN_int1-1)
--SET @LSN1=SUBSTRING(@LSN,@LSN_int1+1,@LSN_int2-@LSN_int1-1)
--SET @LSN2=SUBSTRING(@LSN,@LSN_int2+1,LEN(@LSN))
--PRINT 'CurrentLSN='+@LSN0+':'+@LSN1+':'+@LSN2

--> SQL2005:CAST('' as xml).value('xs:hexBinary(substring(sql:variable("@CurrentLSN"),1,8))','varbinary(max)') == SQL2008:CONVERT(VARBINARY,SUBSTRING(@CurrentLSN,1,8),2)
--DECLARE @str VARCHAR(50)
--SET @str=CONVERT(VARCHAR,CONVERT(INT,CAST('' as xml).value('xs:hexBinary(substring(sql:variable("@CurrentLSN"),1,8))','varbinary(max)')))+':'+
-- CONVERT(VARCHAR,CONVERT(INT,CAST('' as xml).value('xs:hexBinary(substring(sql:variable("@CurrentLSN"),10,8))','varbinary(max)')))+':'+
-- CONVERT(VARCHAR,CONVERT(INT,CAST('' as xml).value('xs:hexBinary(substring(sql:variable("@CurrentLSN"),19,4))','varbinary(max)')))
--PRINT 'CurrentLSN_base10='+@str
--DECLARE @int BIGINT
--SET @int=CONVERT(BIGINT,CONVERT(VARCHAR,CONVERT(INT,CAST('' as xml).value('xs:hexBinary(substring(sql:variable("@CurrentLSN"),1,8))','varbinary(max)')))+
-- RIGHT('0000000000'+CONVERT(VARCHAR,CONVERT(INT,CAST('' as xml).value('xs:hexBinary(substring(sql:variable("@CurrentLSN"),10,8))','varbinary(max)'))),10)+
-- RIGHT('00000'+CONVERT(VARCHAR,CONVERT(INT,CAST('' as xml).value('xs:hexBinary(substring(sql:variable("@CurrentLSN"),19,4))','varbinary(max)'))),5) )
--PRINT 'CurrentLSN_int='+CONVERT(VARCHAR,@int)
END
END

IF @Operation ='LOP_MODIFY_COLUMNS'
BEGIN

/* If the @Operation Type is 'LOP_MODIFY_ROW' then we need to follow a different procedure to recover modified
.Because this time the data is also in chunks but merge with the data log.
*/
--First, we need to get the [RowLog Contents 3] Because in [Log Record] field the modified data is available after the [RowLog Contents 3] data.
SET @RowLogContents3_Var = CAST('' AS XML).value('xs:hexBinary(sql:variable("@RowLogContents3") )', 'varchar(max)')
SET @LogRecord_Var = CAST('' AS XML).value('xs:hexBinary(sql:variable("@LogRecord"))', 'varchar(max)')

---First get the modifed data chunks in string format
SET @RowLogData_Var = SUBSTRING(@LogRecord_Var, CHARINDEX(@RowLogContents3_Var,@LogRecord_Var)+LEN(@RowLogContents3_Var) ,LEN(@LogRecord_Var))
--Then convert it into the hex values.
SELECT @RowLogData_Hex = CAST('' AS XML).value('xs:hexBinary( substring(sql:variable("@RowLogData_Var"),0) )', 'varbinary(max)')
FROM (SELECT CASE SUBSTRING(@RowLogData_Var, 1, 2)WHEN '0x' THEN 3 ELSE 0 END) AS t(pos)

-- Before recovering the modfied data we need to get the total fixed length data size and start position of the varaible data

SELECT @TotalFixedLengthData = CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0] , 2 + 1, 2))))
,@VariableLength_Offset_Start = CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0] , 2 + 1, 2))))+5+CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0] , CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0] , 2 + 1, 2)))) + 1, 2))))/8.0))
FROM @ModifiedRawData
WHERE [Current LSN]=@CurrentLSN

SET @FixedLength_Offset = CONVERT(BINARY(2),REVERSE(CONVERT(BINARY(4),(@RowLogContents0))))--)
SET @VariableLength_Offset = CONVERT(INT,CONVERT(BINARY(2),REVERSE(@RowLogContents0)))

/* We already have modified data chunks in @RowLogData_Hex but this data is in merge format (modified plus actual data)
So , here we need [Row Log Contents 1] field , because in this field we have the data length both the modified and actual data
so this length will help us to break it into original and modified data chunks.
*/
SET @FixedLength_Loc = CONVERT(INT,SUBSTRING(@RowLogContents1,1,1))
SET @VariableLength_Loc = CONVERT(INT,SUBSTRING(@RowLogContents1,3,1))

/*First , we need to break Fix length data actual with the help of data length */
SET @OldFixedLengthStartPosition= CHARINDEX(@RowLogContents4,@RowLogData_Hex)
SET @FixedOldValues = SUBSTRING(@RowLogData_Hex,@OldFixedLengthStartPosition,@FixedLength_Loc)
SET @FixedLengthIncrease = (CASE WHEN (Len(@FixedOldValues)%4) = 0 THEN 1 ELSE (4-(LEN(@FixedOldValues)%4)) END)
/*After that , we need to break Fix length data modified data with the help of data length */
SET @FixedNewValues =SUBSTRING(@RowLogData_Hex,@OldFixedLengthStartPosition+@FixedLength_Loc+@FixedLengthIncrease,@FixedLength_Loc)

/*Same we need to break the variable data with the help of data length*/
SET @VariableOldValues =SUBSTRING(@RowLogData_Hex,@OldFixedLengthStartPosition+@FixedLength_Loc+@FixedLengthIncrease+@FixedLength_Loc+(@FixedLengthIncrease),@VariableLength_Loc)
SET @VariableLengthIncrease = (CASE WHEN (LEN(@VariableOldValues)%4) = 0 THEN 1 ELSE (4-(Len(@VariableOldValues)%4))+1 END)
SET @VariableOldValues = (Case When @VariableLength_Loc = 1 Then @VariableOldValues+0x00 else @VariableOldValues end)

SET @VariableNewValues = SUBSTRING(SUBSTRING(@RowLogData_Hex,@OldFixedLengthStartPosition+@FixedLength_Loc+@FixedLengthIncrease+@FixedLength_Loc+(@FixedLengthIncrease-1)+@VariableLength_Loc+@VariableLengthIncrease,Len(@RowLogData_Hex)+1),1,Len(@RowLogData_Hex)+1) --LEN(@VariableOldValues)

/*here we need to replace the fixed length & variable length actaul data with modifed data
*/

SELECT @VariableNewValues=CASE
WHEN Charindex(Substring(@VariableNewValues,0,Len(@VariableNewValues)+1),[RowLog Contents 0])<>0 Then Substring(@VariableNewValues,0,Len(@VariableNewValues)+1)
WHEN Charindex(Substring(@VariableNewValues,0,Len(@VariableNewValues) ),[RowLog Contents 0])<>0 Then Substring(@VariableNewValues,0,Len(@VariableNewValues))
WHEN Charindex(Substring(@VariableNewValues,0,Len(@VariableNewValues)-1),[RowLog Contents 0])<>0 Then Substring(@VariableNewValues,0,Len(@VariableNewValues)-1)--3 --Substring(@VariableNewValues,0,Len(@VariableNewValues)-1)
WHEN Charindex(Substring(@VariableNewValues,0,Len(@VariableNewValues)-2),[RowLog Contents 0])<>0 Then Substring(@VariableNewValues,0,Len(@VariableNewValues)-2)
WHEN Charindex(Substring(@VariableNewValues,0,Len(@VariableNewValues)-3),[RowLog Contents 0])<>0 Then Substring(@VariableNewValues,0,Len(@VariableNewValues)-3) --5--Substring(@VariableNewValues,0,Len(@VariableNewValues)-3)
END
FROM @ModifiedRawData
WHERE [Current LSN]=@CurrentLSN

INSERT INTO @ModifiedRawData ([PAGE ID],[Slot ID],[AllocUnitId],[Datum],[TRANSACTION ID],[Transaction Name],[Current LSN],[Begin Time],[RowLog Contents 0_var],[RowLog Contents 0],[Slot Info])
SELECT @ConsolidatedPageID AS [PAGE ID],@Slotid AS [Slot ID],@AllocUnitID AS [AllocUnitId],'Restoration' AS [Datum],@TransactionID AS [TRANSACTION ID],@TransactionName AS [Transaction Name],@CurrentLSN AS [Current LSN],@BeginTime AS [Begin Time]
,NULL --> [RowLog Contents 0_var]
,ISNULL( --> due to chained updates; this only works on the most recent update
CAST(REPLACE(SUBSTRING([RowLog Contents 0],0,@TotalFixedLengthData+1),@FixedNewValues, @FixedOldValues) AS VARBINARY(max))
+ SUBSTRING([RowLog Contents 0], @TotalFixedLengthData + 1, 2)
+ SUBSTRING([RowLog Contents 0], @TotalFixedLengthData + 3, CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], @TotalFixedLengthData + 1, 2))))/8.0)))
+ SUBSTRING([RowLog Contents 0], @TotalFixedLengthData + 3 + CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], @TotalFixedLengthData + 1, 2))))/8.0)), 2)
+ SUBSTRING([RowLog Contents 0],@VariableLength_Offset_Start,(@VariableLength_Offset-(@VariableLength_Offset_Start-1)))
+ CAST(REPLACE(SUBSTRING([RowLog Contents 0],@VariableLength_Offset+1,Len(@VariableNewValues))
,@VariableNewValues,@VariableOldValues) AS VARBINARY)
+ Substring([RowLog Contents 0],@VariableLength_Offset+Len(@VariableNewValues)+1,LEN([RowLog Contents 0]))
,[RowLog Contents 0]) --> [RowLog Contents 0]
,[Slot Info]
FROM @ModifiedRawData
WHERE [Current LSN]=@CurrentLSN

--> Convert the old data which is in hex format to string format (not required).
UPDATE @ModifiedRawData SET [RowLog Contents 0_var] = CAST('' AS XML).value('xs:hexBinary(sql:column("[RowLog Contents 0]") )', 'varchar(max)')
FROM @ModifiedRawData
WHERE [Current LSN]=@CurrentLSN
END

FETCH NEXT FROM Page_Data_Cursor INTO @ConsolidatedPageID,@Slotid,@AllocUnitID,@TransactionID,@TransactionName,@CurrentLSN,@BeginTime,@RowLogContents0,@RowLogContents1,@RowLogContents2,@RowLogContents3,@RowLogContents4,@LogRecord,@Operation
END

CLOSE Page_Data_Cursor
DEALLOCATE Page_Data_Cursor
/*******************CURSOR END*********************/
------------------------------------------------------------------------------------------------------------
DECLARE @ModRawDataLoop INT
--> Add sequence index number(s)
UPDATE A SET [EntryID] = B.[index] FROM @ModifiedRawData A
JOIN (SELECT ROW_NUMBER() OVER (ORDER BY [Current LSN],[Datum] DESC) AS [index], [ID] FROM @ModifiedRawData) B ON
B.[ID] = A.[ID]
--> Add backward reference(s) and forward reference(s)
UPDATE A SET
[PrevEntry] =
ISNULL((SELECT MAX(B.[EntryID]) AS [EntryID] FROM @ModifiedRawData B
WHERE B.[Slot ID] = A.[Slot ID] AND B.[EntryID] < A.[EntryID]),0)
,[NextEntry] =
ISNULL((SELECT MIN(B.[EntryID]) AS [EntryID] FROM @ModifiedRawData B
WHERE B.[Slot ID] = A.[Slot ID] AND B.[EntryID] > A.[EntryID]),0)
FROM @ModifiedRawData A
--> Add chain level(s)
UPDATE A SET [ChainLevel] = B.[index] FROM @ModifiedRawData A
JOIN (SELECT DENSE_RANK() OVER (PARTITION BY [SLOT ID] ORDER BY [Current LSN])-1 AS [index], [ID] FROM @ModifiedRawData) B ON
B.[ID] = A.[ID]
--> Set the process order(s) --> the reverse of the [ChainLevel]
UPDATE A SET
[Process] = CASE WHEN ([ChainLevel] = 0) THEN 0
ELSE (SELECT MAX([ChainLevel]) FROM @ModifiedRawData B WHERE B.[Slot ID] = A.[Slot ID]) - [ChainLevel]
END
FROM @ModifiedRawData A
--select * from @ModifiedRawData order by [EntryID]

--> Get the chained UPDATE records (forward in time) to locate the replaced "Reference" record(s) (chained UPDATEs)
SELECT B.* INTO #T1
FROM @ModifiedRawData A
INNER JOIN @ModifiedRawData B ON B.[Transaction Name] = 'UPDATE'
AND B.[NextEntry] = A.[EntryID]
AND B.[Datum] = 'Reference' AND A.[Datum] = 'Restoration'
--AND B.[Current LSN] <> A.[Current LSN] --> should always be true
SET @ModRawDataLoop = @@ROWCOUNT
--select * from #T1

IF (@ModRawDataLoop > 0) BEGIN
WHILE (@ModRawDataLoop > 0) BEGIN
/*
If the [Operation] Type is 'LOP_MODIFY_ROW' then it is very simple to recover the modified data. The old data is in [RowLog Contents 0] Field and modified data is in [RowLog Contents 1] Field. Simply replace it with the modified data and get the old data.
*/
--> First, change the byte of [RowLog Contents 0_var] that may differ from the first byte of [RowLog Contents 1_var] (I don't know why these don't match sometimes)
--> Fix the copy before it is restored back into the applicable records (next)
UPDATE #T1 SET
[RowLog Contents 0_var] =
SUBSTRING(B.[RowLog Contents 0_var],1,PATINDEX('%'+SUBSTRING(A.[RowLog Contents 1_var],3,LEN(A.[RowLog Contents 1_var]))+'%',B.[RowLog Contents 0_var])-3)
+SUBSTRING(A.[RowLog Contents 1_var],1,2)
+SUBSTRING(B.[RowLog Contents 0_var],PATINDEX('%'+SUBSTRING(A.[RowLog Contents 1_var],3,LEN(A.[RowLog Contents 1_var]))+'%',B.[RowLog Contents 0_var]),LEN(B.[RowLog Contents 0_var]))
,[RowLog Contents 0] =
SUBSTRING(B.[RowLog Contents 0],1,PATINDEX('%'+SUBSTRING(A.[RowLog Contents 1_var],3,LEN(A.[RowLog Contents 1_var]))+'%',B.[RowLog Contents 0_var])/2-1)
+SUBSTRING(A.[RowLog Contents 1],1,1)
+SUBSTRING(B.[RowLog Contents 0],PATINDEX('%'+SUBSTRING(A.[RowLog Contents 1_var],3,LEN(A.[RowLog Contents 1_var]))+'%',B.[RowLog Contents 0_var])/2+1,LEN(B.[RowLog Contents 0]))
FROM @PreliminaryRawData A
INNER JOIN #T1 C ON C.[Current LSN] = A.[Current LSN]
INNER JOIN @ModifiedRawData B ON B.[EntryID] = C.[NextEntry] --> source location
WHERE A.[Operation] IN ('LOP_MODIFY_ROW') AND C.[Process] = 1
--select * from #T1
--> Restore (one level) the replaced (and therefore lost) "Reference" information (chained UPDATEs)
-- for both the "Reference" and "Restoration" records, and the original source record
UPDATE @ModifiedRawData SET
[RowLog Contents 0_var] = B.[RowLog Contents 0_var]
,[RowLog Contents 0] = B.[RowLog Contents 0]
FROM @ModifiedRawData A
INNER JOIN #T1 B ON A.[EntryID] IN (B.[EntryID],B.[PrevEntry],B.[NextEntry])
WHERE B.[Process] = 1
--select * from @ModifiedRawData order by [EntryID]
--> Now, the substitution will work, so update [RowLog Contents 0_var]
UPDATE @ModifiedRawData SET
[RowLog Contents 0_var] =
--> look for the UPDATE mate from the previous record pull
REPLACE(UPPER(B.[RowLog Contents 0_var]),UPPER(CAST('' AS XML).value('xs:hexBinary(sql:column("A.[RowLog Contents 1]") )','varchar(max)')),UPPER(CAST('' AS XML).value('xs:hexBinary(sql:column("A.[RowLog Contents 0]") )','varchar(max)')))
,[RowLog Contents 0] = NULL
FROM @PreliminaryRawData A
INNER JOIN @ModifiedRawData B ON B.[Current LSN]=A.[Current LSN]
INNER JOIN #T1 C ON C.[PrevEntry] = B.[EntryID]
WHERE A.[Operation] IN ('LOP_MODIFY_ROW') AND B.[Process] = 1

-- Convert the old data which is in string format to hex format (required).
UPDATE @ModifiedRawData SET
[RowLog Contents 0] = CAST('' AS XML).value('xs:hexBinary(substring(sql:column("[RowLog Contents 0_var]"), 0) )', 'varbinary(max)')
FROM @ModifiedRawData
WHERE [RowLog Contents 0] IS NULL
SET @ModRawDataLoop = @@ROWCOUNT
--print '@ModRawDataLoop (LOP_MODIFY_ROW)= '+CONVERT(varchar,@ModRawDataLoop)
--select * from @ModifiedRawData order by [EntryID]

/*******************CURSOR START*********************/
---Now we have modifed data plus its slot ID , page ID and allocunit as well.
--After that we need to get the old values before modfication, these data are in chunks.
DECLARE Page_Data_Cursor CURSOR FOR
SELECT A.[PAGE ID],A.[Slot ID],A.[AllocUnitId],A.[TRANSACTION ID],A.[Transaction Name],A.[Current LSN],A.[Begin Time],A.[RowLog Contents 0],[RowLog Contents 1],[RowLog Contents 2],[RowLog Contents 3],[RowLog Contents 4],[Log Record],[Operation]
FROM @PreliminaryRawData A
INNER JOIN @ModifiedRawData B ON B.[Current LSN] = A.[Current LSN] --> skip this section if there are no updates
WHERE [Operation] IN ('LOP_MODIFY_COLUMNS') AND B.[Process] = 1 AND B.[Datum] = 'Restoration'
ORDER BY A.[Slot ID],A.[TRANSACTION ID] DESC

SET @ModRawDataLoop = 0
/****************************************/

OPEN Page_Data_Cursor

FETCH NEXT FROM Page_Data_Cursor INTO @ConsolidatedPageID,@Slotid,@AllocUnitID,@TransactionID,@TransactionName,@CurrentLSN,@BeginTime,@RowLogContents0,@RowLogContents1,@RowLogContents2,@RowLogContents3,@RowLogContents4,@LogRecord,@Operation
WHILE @@FETCH_STATUS = 0
BEGIN
--IF @Operation ='LOP_MODIFY_COLUMNS'
BEGIN

/* If the @Operation Type is 'LOP_MODIFY_ROW' then we need to follow a different procedure to recover modified
.Because this time the data is also in chunks but merge with the data log.
*/
--First, we need to get the [RowLog Contents 3] Because in [Log Record] field the modified data is available after the [RowLog Contents 3] data.
SET @RowLogContents3_Var = CAST('' AS XML).value('xs:hexBinary(sql:variable("@RowLogContents3") )', 'varchar(max)')
SET @LogRecord_Var = CAST('' AS XML).value('xs:hexBinary(sql:variable("@LogRecord"))', 'varchar(max)')

---First get the modifed data chunks in string format
SET @RowLogData_Var = SUBSTRING(@LogRecord_Var, CHARINDEX(@RowLogContents3_Var,@LogRecord_Var)+LEN(@RowLogContents3_Var) ,LEN(@LogRecord_Var))
--Then convert it into the hex values.
SELECT @RowLogData_Hex = CAST('' AS XML).value('xs:hexBinary( substring(sql:variable("@RowLogData_Var"),0) )', 'varbinary(max)')
FROM (SELECT CASE SUBSTRING(@RowLogData_Var, 1, 2)WHEN '0x' THEN 3 ELSE 0 END) AS t(pos)

-- Before recovering the modfied data we need to get the total fixed length data size and start position of the varaible data

SELECT @TotalFixedLengthData = CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0] , 2 + 1, 2))))
,@VariableLength_Offset_Start = CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0] , 2 + 1, 2))))+5+CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0] , CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0] , 2 + 1, 2)))) + 1, 2))))/8.0))
FROM @ModifiedRawData
WHERE [Current LSN]=@CurrentLSN

SET @FixedLength_Offset = CONVERT(BINARY(2),REVERSE(CONVERT(BINARY(4),(@RowLogContents0))))--)
SET @VariableLength_Offset = CONVERT(INT,CONVERT(BINARY(2),REVERSE(@RowLogContents0)))

/* We already have modified data chunks in @RowLogData_Hex but this data is in merge format (modified plus actual data)
So , here we need [Row Log Contents 1] field , because in this field we have the data length both the modified and actual data
so this length will help us to break it into original and modified data chunks.
*/
SET @FixedLength_Loc = CONVERT(INT,SUBSTRING(@RowLogContents1,1,1))
SET @VariableLength_Loc = CONVERT(INT,SUBSTRING(@RowLogContents1,3,1))

/*First , we need to break Fix length data actual with the help of data length */
SET @OldFixedLengthStartPosition= CHARINDEX(@RowLogContents4,@RowLogData_Hex)
SET @FixedOldValues = SUBSTRING(@RowLogData_Hex,@OldFixedLengthStartPosition,@FixedLength_Loc)
SET @FixedLengthIncrease = (CASE WHEN (Len(@FixedOldValues)%4) = 0 THEN 1 ELSE (4-(LEN(@FixedOldValues)%4)) END)
/*After that , we need to break Fix length data modified data with the help of data length */
SET @FixedNewValues =SUBSTRING(@RowLogData_Hex,@OldFixedLengthStartPosition+@FixedLength_Loc+@FixedLengthIncrease,@FixedLength_Loc)

/*Same we need to break the variable data with the help of data length*/
SET @VariableOldValues =SUBSTRING(@RowLogData_Hex,@OldFixedLengthStartPosition+@FixedLength_Loc+@FixedLengthIncrease+@FixedLength_Loc+(@FixedLengthIncrease),@VariableLength_Loc)
SET @VariableLengthIncrease = (CASE WHEN (LEN(@VariableOldValues)%4) = 0 THEN 1 ELSE (4-(Len(@VariableOldValues)%4))+1 END)
SET @VariableOldValues = (Case When @VariableLength_Loc = 1 Then @VariableOldValues+0x00 else @VariableOldValues end)

SET @VariableNewValues = SUBSTRING(SUBSTRING(@RowLogData_Hex,@OldFixedLengthStartPosition+@FixedLength_Loc+@FixedLengthIncrease+@FixedLength_Loc+(@FixedLengthIncrease-1)+@VariableLength_Loc+@VariableLengthIncrease,Len(@RowLogData_Hex)+1),1,Len(@RowLogData_Hex)+1) --LEN(@VariableOldValues)

/*here we need to replace the fixed length & variable length actaul data with modifed data
*/

SELECT @VariableNewValues=CASE
WHEN Charindex(Substring(@VariableNewValues,0,Len(@VariableNewValues)+1),[RowLog Contents 0])<>0 Then Substring(@VariableNewValues,0,Len(@VariableNewValues)+1)
WHEN Charindex(Substring(@VariableNewValues,0,Len(@VariableNewValues) ),[RowLog Contents 0])<>0 Then Substring(@VariableNewValues,0,Len(@VariableNewValues))
WHEN Charindex(Substring(@VariableNewValues,0,Len(@VariableNewValues)-1),[RowLog Contents 0])<>0 Then Substring(@VariableNewValues,0,Len(@VariableNewValues)-1)--3 --Substring(@VariableNewValues,0,Len(@VariableNewValues)-1)
WHEN Charindex(Substring(@VariableNewValues,0,Len(@VariableNewValues)-2),[RowLog Contents 0])<>0 Then Substring(@VariableNewValues,0,Len(@VariableNewValues)-2)
WHEN Charindex(Substring(@VariableNewValues,0,Len(@VariableNewValues)-3),[RowLog Contents 0])<>0 Then Substring(@VariableNewValues,0,Len(@VariableNewValues)-3) --5--Substring(@VariableNewValues,0,Len(@VariableNewValues)-3)
END
FROM @ModifiedRawData
WHERE [Current LSN]=@CurrentLSN

UPDATE @ModifiedRawData SET
[RowLog Contents 0] =
CAST(REPLACE(SUBSTRING([RowLog Contents 0],0,@TotalFixedLengthData+1),@FixedNewValues, @FixedOldValues) AS VARBINARY(max))
+ SUBSTRING([RowLog Contents 0], @TotalFixedLengthData + 1, 2)
+ SUBSTRING([RowLog Contents 0], @TotalFixedLengthData + 3, CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], @TotalFixedLengthData + 1, 2))))/8.0)))
+ SUBSTRING([RowLog Contents 0], @TotalFixedLengthData + 3 + CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], @TotalFixedLengthData + 1, 2))))/8.0)), 2)
+ SUBSTRING([RowLog Contents 0],@VariableLength_Offset_Start,(@VariableLength_Offset-(@VariableLength_Offset_Start-1)))
+ CAST(REPLACE(SUBSTRING([RowLog Contents 0],@VariableLength_Offset+1,Len(@VariableNewValues))
,@VariableNewValues,@VariableOldValues) AS VARBINARY)
+ Substring([RowLog Contents 0],@VariableLength_Offset+Len(@VariableNewValues)+1,LEN([RowLog Contents 0]))
,[RowLog Contents 0_var] = NULL
FROM @ModifiedRawData
WHERE [Current LSN]=@CurrentLSN AND [Process] = 1 AND [Datum] = 'Restoration'

--> Convert the old data which is in hex format to string format (not required).
UPDATE @ModifiedRawData SET [RowLog Contents 0_var] = CAST('' AS XML).value('xs:hexBinary(sql:column("[RowLog Contents 0]") )', 'varchar(max)')
FROM @ModifiedRawData
WHERE [RowLog Contents 0_var] IS NULL
SET @ModRawDataLoop = @ModRawDataLoop + @@ROWCOUNT

END

FETCH NEXT FROM Page_Data_Cursor INTO @ConsolidatedPageID,@Slotid,@AllocUnitID,@TransactionID,@TransactionName,@CurrentLSN,@BeginTime,@RowLogContents0,@RowLogContents1,@RowLogContents2,@RowLogContents3,@RowLogContents4,@LogRecord,@Operation
END
--print '@ModRawDataLoop (LOP_MODIFY_COLUMNS)= '+CONVERT(varchar,@ModRawDataLoop)

CLOSE Page_Data_Cursor
DEALLOCATE Page_Data_Cursor
/*******************CURSOR END*********************/
--select * from @ModifiedRawData order by [EntryID]

--> Update the process order
UPDATE #T1 SET [Process] = [Process] - 1
FROM #T1
WHERE [Process] > 0
SET @ModRawDataLoop = (SELECT COUNT(*) FROM #T1 WHERE [Process] > 0)
--print '@ModRawDataLoop (remaining)= '+CONVERT(varchar,@ModRawDataLoop)

IF (@ModRawDataLoop > 0) BEGIN
--> Update the process order
UPDATE @ModifiedRawData SET [Process] = [Process] - 1
FROM @ModifiedRawData
WHERE [Process] > 0

--> Now look ahead and get (temporarily store) the replaced "Reference" information (chained UPDATEs)
-- this is required for UPDATEs occurring before the most recent UPDATE
UPDATE #T1 SET --> redundant the for the first level
[RowLog Contents 0_var] = A.[RowLog Contents 0_var]
,[RowLog Contents 0] = A.[RowLog Contents 0]
FROM @ModifiedRawData A
INNER JOIN #T1 B ON B.[NextEntry] = A.[EntryID]
WHERE B.[Process] = 1
--select * from #T1
END
END
END
------------------------------------------------------------------------------------------------------------
IF (@Debug > 0) BEGIN
print 'select * from @ModifiedRawData2'
select '@ModifiedRawData2'
select * from @ModifiedRawData ORDER BY [Current LSN], [Datum] Desc
END

DECLARE @RowLogContents VARBINARY(8000)
DECLARE @AllocUnitName NVARCHAR(MAX)
DECLARE @SQL NVARCHAR(MAX)

DECLARE @bitTable TABLE(
[ID] INT
,[Bitvalue] INT
)
--Create table to set the bit position of one byte.

INSERT INTO @bitTable
SELECT 0,2 UNION ALL
SELECT 1,2 UNION ALL
SELECT 2,4 UNION ALL
SELECT 3,8 UNION ALL
SELECT 4,16 UNION ALL
SELECT 5,32 UNION ALL
SELECT 6,64 UNION ALL
SELECT 7,128

--Create table to collect the row data.
DECLARE @DeletedRecords TABLE(
[ID] INT IDENTITY(1,1)
,[RowLogContents] VARBINARY(8000)
,[AllocUnitID] BIGINT
,[TransactionID] NVARCHAR(Max)
,[Slot ID] INT
,[FixedLengthData] SMALLINT
,[TotalNoOfCols] SMALLINT
,[NullBitMapLength] SMALLINT
,[NullBytes] VARBINARY(8000)
,[TotalNoOfVarCols] SMALLINT
,[ColumnOffsetArray] VARBINARY(8000)
,[VarColumnStart] SMALLINT
,[NullBitMap] VARCHAR(MAX)
,[TRANSACTION ID] NVARCHAR(Max)
,[Transaction Name] NVARCHAR(MAX)
,[Datum] VARCHAR(20)
,[Current LSN] VARCHAR(MAX)
,[Begin Time] DATETIME
)
--Create a common table expression to get all the row data plus how many bytes we have for each row.
;WITH RowData AS
(SELECT
[RowLog Contents 0] AS [RowLogContents]
,[AllocUnitID]
,[ID] AS [TransactionID]
,[Slot ID] as [Slot ID]
--[Fixed Length Data] = Substring (RowLog content 0, Status Bit A+ Status Bit B + 1,2 bytes)
,CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) AS [FixedLengthData] --@FixedLengthData

--[TotalnoOfCols] = Substring (RowLog content 0, [Fixed Length Data] + 1,2 bytes)
,CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2),
REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2)))) as [TotalNoOfCols]

--[NullBitMapLength]=ceiling([Total No of Columns] /8.0)
,CONVERT(INT, CEILING(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2),
REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)) as [NullBitMapLength]

--[Null Bytes] = Substring (RowLog content 0, Status Bit A+ Status Bit B + [Fixed Length Data] +1, [NullBitMapLength] )
,SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 3,
CONVERT(INT, CEILING(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2),
REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0))) as [NullBytes]

--[TotalNoOfVarCols] = Substring (RowLog content 0, Status Bit A+ Status Bit B + [Fixed Length Data] +1, [Null Bitmap length] + 2 )
,(CASE WHEN SUBSTRING([RowLog Contents 0], 1, 1) In (0x30,0x70)
THEN CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0],
CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 3 +
CONVERT(INT, CEILING(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2),
REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)), 2))))
ELSE null END) AS [TotalNoOfVarCols]

--[ColumnOffsetArray]= Substring (RowLog content 0, Status Bit A+ Status Bit B + [Fixed Length Data] +1, [Null Bitmap length] + 2 , [TotalNoOfVarCols]*2 )
,(CASE WHEN SUBSTRING([RowLog Contents 0], 1, 1) In (0x30,0x70)
THEN SUBSTRING([RowLog Contents 0],
CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 3 +
CONVERT(INT, CEILING(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2),
REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)) + 2,
(CASE WHEN SUBSTRING([RowLog Contents 0], 1, 1) In (0x30,0x70)
THEN CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0],
CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 3 +
CONVERT(INT, CEILING(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2),
REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)), 2))))
ELSE null END) * 2)
ELSE null END) AS [ColumnOffsetArray]

-- Variable column Start = Status Bit A+ Status Bit B + [Fixed Length Data] + [Null Bitmap length] + 2+([TotalNoOfVarCols]*2)
,CASE WHEN SUBSTRING([RowLog Contents 0], 1, 1)In (0x30,0x70)
THEN (CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 4 +
CONVERT(INT, CEILING(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2),
REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)) +
((CASE WHEN SUBSTRING([RowLog Contents 0], 1, 1) In (0x30,0x70)
THEN CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0],
CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 3 +
CONVERT(INT, CEILING(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2),
REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)), 2))))
ELSE null END) * 2))
ELSE NULL END AS [VarColumnStart]
,[TRANSACTION ID]
,[Transaction Name]
,[Datum]
,[Current LSN]
,[Begin Time]
FROM @ModifiedRawData
)

---Use this technique to repeat the row till the no of bytes of the row.
,N1 (n) AS (SELECT 1 UNION ALL SELECT 1)
,N2 (n) AS (SELECT 1 FROM N1 AS X, N1 AS Y)
,N3 (n) AS (SELECT 1 FROM N2 AS X, N2 AS Y)
,N4 (n) AS (SELECT ROW_NUMBER() OVER(ORDER BY X.n) FROM N3 AS X, N3 AS Y)

INSERT INTO @DeletedRecords
SELECT [RowLogContents]
,[AllocUnitID]
,[TransactionID]
,[Slot ID]
,[FixedLengthData]
,[TotalNoOfCols]
,[NullBitMapLength]
,[NullBytes]
,[TotalNoOfVarCols]
,[ColumnOffsetArray]
,[VarColumnStart]
--Get the Null value against each column (1 means null zero means not null)
,[NullBitMap]=(REPLACE(STUFF(
(SELECT ',' +
(CASE WHEN [ID]=0 THEN CONVERT(NVARCHAR(1),(SUBSTRING(NullBytes, n, 1) % 2)) ELSE CONVERT(NVARCHAR(1),((SUBSTRING(NullBytes, n, 1) / [Bitvalue]) % 2)) END) --as [nullBitMap]
FROM N4 AS Nums
JOIN RowData AS C ON n <= NullBitMapLength
CROSS JOIN @bitTable WHERE C.[RowLogContents] = D.[RowLogContents]
ORDER BY [RowLogContents],n ASC FOR XML PATH('')
),1,1,''),',',''))
,[TRANSACTION ID]
,[Transaction Name]
,[Datum]
,[Current LSN]
,[Begin Time]
FROM RowData D
IF (@Debug > 0) BEGIN
print 'select * from @DeletedRecords'
select '@DeletedRecords'
select * from @DeletedRecords
END

CREATE TABLE [#temp_Data](
[FieldName] VARCHAR(MAX) COLLATE database_default NOT NULL
,[FieldValue] VARCHAR(MAX) COLLATE database_default NULL
,[FieldSetValue] VARCHAR(MAX) COLLATE database_default NULL
,[Rowlogcontents] VARBINARY(8000)
,[TransactionID] VARCHAR(MAX) COLLATE database_default NOT NULL
,[Slot ID] INT
,[NonID] INT
,[nullbit] INT
,[TRANSACTION ID] NVARCHAR(MAX)
,[Transaction Name] NVARCHAR(MAX)
,[Datum] VARCHAR(20)
,[Current LSN] VARCHAR(MAX)
,[Begin Time] DATETIME
--,[System_type_id] INT
)
--Create common table expression and join it with the rowdata table
--to get each column details
;With CTE AS
/*This part is for variable data columns*/
(SELECT
A.[ID]
,[Rowlogcontents]
,[TransactionID]
,[Slot ID]
,[TRANSACTION ID]
,[Transaction Name]
,[Datum]
,[Current LSN]
,[Begin Time]
,[NAME]
,cols.leaf_null_bit AS nullbit
,leaf_offset
,ISNULL(syscolumns.length, cols.max_length) AS [length]
,cols.system_type_id
,cols.leaf_bit_position AS bitpos
,ISNULL(syscolumns.xprec, cols.precision) AS xprec
,ISNULL(syscolumns.xscale, cols.scale) AS xscale
,SUBSTRING([nullBitMap], cols.leaf_null_bit, 1) AS is_null
--Calculate the variable column size from the variable column offset array
,(CASE WHEN leaf_offset<1 AND SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0
THEN CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*(leaf_offset*-1))-1, 2))))
ELSE 0 END
) AS [Column value Size]

--Calculate the column length
,(CASE WHEN leaf_offset<1 AND SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0
THEN CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING ([ColumnOffsetArray], (2*(leaf_offset*-1))-1, 2))))
- ISNULL(NULLIF(CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE (SUBSTRING([ColumnOffsetArray], (2*((leaf_offset*-1)-1))-1, 2)))), 0), [varColumnStart]) --> If Null OR zero
ELSE 0 END
) AS [Column Length]

--Get the Hexa decimal value from the RowlogContent
--HexValue of the variable column=Substring([Column value Size] - [Column Length] + 1,[Column Length])
--This is the data of your column but in the Hexvalue
,CASE WHEN SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=1
THEN NULL
ELSE SUBSTRING(Rowlogcontents,
(
(CASE WHEN leaf_offset<1 AND SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0
THEN CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*(leaf_offset*-1))-1, 2))))
ELSE 0 END
)
-(
(CASE WHEN leaf_offset<1 AND SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0
THEN CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*(leaf_offset*-1))-1, 2))))
- ISNULL(NULLIF(CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*((leaf_offset*-1)-1))-1, 2)))), 0), [varColumnStart]) --> If Null OR zero
ELSE 0 END
))
)+1,(
(CASE WHEN leaf_offset<1 AND SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0
THEN CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*(leaf_offset*-1))-1, 2))))
- ISNULL(NULLIF(CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*((leaf_offset*-1)-1))-1, 2)))), 0), [varColumnStart]) --> If Null OR zero
ELSE 0 END
))
)
END AS hex_Value

FROM @DeletedRecords A
INNER JOIN sys.allocation_units allocunits ON
A.[AllocUnitId]=allocunits.[Allocation_Unit_Id]
INNER JOIN sys.partitions partitions ON
(allocunits.type IN (1, 3) AND partitions.hobt_id = allocunits.container_id)
OR (allocunits.type = 2 AND partitions.partition_id = allocunits.container_id)
INNER JOIN sys.system_internals_partition_columns cols ON cols.partition_id = partitions.partition_id
LEFT OUTER JOIN syscolumns ON syscolumns.id = partitions.object_id AND syscolumns.colid = cols.partition_column_id
WHERE leaf_offset < 0

UNION
/*This part is for fixed data columns*/
SELECT
A.[ID]
,[Rowlogcontents]
,[TransactionID]
,[Slot ID]
,[TRANSACTION ID]
,[Transaction Name]
,[Datum]
,[Current LSN]
,[Begin Time]
,[NAME]
,cols.leaf_null_bit AS [nullbit]
,leaf_offset
,ISNULL(syscolumns.length, cols.max_length) AS [length]
,cols.system_type_id
,cols.leaf_bit_position AS bitpos
,ISNULL(syscolumns.xprec, cols.precision) AS xprec
,ISNULL(syscolumns.xscale, cols.scale) AS xscale
,SUBSTRING([nullBitMap], cols.leaf_null_bit, 1) AS is_null
,(SELECT TOP 1 ISNULL(SUM(CASE WHEN C.leaf_offset >1 THEN max_length ELSE 0 END),0)
FROM sys.system_internals_partition_columns C
WHERE cols.partition_id=C.partition_id AND C.leaf_null_bit<cols.leaf_null_bit
)+5 AS [Column value Size]
,syscolumns.length AS [Column Length]

,CASE WHEN SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=1
THEN NULL
ELSE SUBSTRING(Rowlogcontents,
(SELECT TOP 1 ISNULL(SUM(CASE WHEN C.leaf_offset >1 THEN max_length ELSE 0 END),0)
FROM sys.system_internals_partition_columns C
WHERE cols.partition_id =C.partition_id AND C.leaf_null_bit<cols.leaf_null_bit
)+5
,syscolumns.length)
END AS hex_Value
FROM @DeletedRecords A
INNER JOIN sys.allocation_units allocunits ON
A.[AllocUnitId]=allocunits.[Allocation_Unit_Id]
INNER JOIN sys.partitions partitions ON
(allocunits.type IN (1, 3) AND partitions.hobt_id = allocunits.container_id)
OR (allocunits.type = 2 AND partitions.partition_id = allocunits.container_id)
INNER JOIN sys.system_internals_partition_columns cols ON cols.partition_id = partitions.partition_id
LEFT OUTER JOIN syscolumns ON syscolumns.id = partitions.object_id AND syscolumns.colid = cols.partition_column_id
WHERE leaf_offset>0
)
--Converting data from Hexvalue to its orgional datatype.
--Implemented datatype conversion mechanism for each datatype
--Select * from sys.columns Where [object_id]=object_id('' + @SchemaName_n_TableName + '')
--Select * from CTE
INSERT INTO #temp_Data
SELECT
NAME,
CASE
WHEN system_type_id IN (231, 239) THEN LTRIM(RTRIM(CONVERT(NVARCHAR(max),hex_Value))) --NVARCHAR ,NCHAR
WHEN system_type_id IN (167,175) THEN LTRIM(RTRIM(CONVERT(VARCHAR(max),REPLACE(hex_Value, 0x00, 0x20)))) --VARCHAR,CHAR
WHEN system_type_id = 48 THEN CONVERT(VARCHAR(MAX), CONVERT(TINYINT, CONVERT(BINARY(1), REVERSE (hex_Value)))) --TINY INTEGER
WHEN system_type_id = 52 THEN CONVERT(VARCHAR(MAX), CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE (hex_Value)))) --SMALL INTEGER
WHEN system_type_id = 56 THEN CONVERT(VARCHAR(MAX), CONVERT(INT, CONVERT(BINARY(4), REVERSE(hex_Value)))) -- INTEGER
WHEN system_type_id = 127 THEN CONVERT(VARCHAR(MAX), CONVERT(BIGINT, CONVERT(BINARY(8), REVERSE(hex_Value))))-- BIG INTEGER
WHEN system_type_id = 61 Then CONVERT(VARCHAR(MAX),CONVERT(DATETIME,CONVERT(VARBINARY(8000),REVERSE (hex_Value))),100) --DATETIME
--WHEN system_type_id IN( 40) Then CONVERT(VARCHAR(MAX),CONVERT(DATE,CONVERT(VARBINARY(8000),(hex_Value))),100) --DATE This datatype only works for SQL Server 2008
WHEN system_type_id =58 Then CONVERT(VARCHAR(MAX),CONVERT(SMALLDATETIME,CONVERT(VARBINARY(8000),REVERSE(hex_Value))),100) --SMALL DATETIME
WHEN system_type_id = 108 THEN CONVERT(VARCHAR(MAX), CAST(CONVERT(NUMERIC(38,30), CONVERT(VARBINARY,CONVERT(VARBINARY,xprec)+CONVERT(VARBINARY,xscale))+CONVERT(VARBINARY(1),0) + hex_Value) as FLOAT)) --- NUMERIC
WHEN system_type_id In(60,122) THEN CONVERT(VARCHAR(MAX),Convert(MONEY,Convert(VARBINARY(8000),Reverse(hex_Value))),2) --MONEY,SMALLMONEY
WHEN system_type_id =106 THEN CONVERT(VARCHAR(MAX), CAST(CONVERT(Decimal(38,34), CONVERT(VARBINARY,Convert(VARBINARY,xprec)+CONVERT(VARBINARY,xscale))+CONVERT(VARBINARY(1),0) + hex_Value) as FLOAT)) --- DECIMAL
WHEN system_type_id = 104 THEN CONVERT(VARCHAR(MAX),CONVERT (BIT,CONVERT(BINARY(1), hex_Value)%2)) -- BIT
WHEN system_type_id =62 THEN RTRIM(LTRIM(STR(CONVERT(FLOAT,SIGN(CAST(CONVERT(VARBINARY(8000),Reverse(hex_Value)) AS BIGINT)) * (1.0 + (CAST(CONVERT(VARBINARY(8000),Reverse(hex_Value)) AS BIGINT) & 0x000FFFFFFFFFFFFF) * POWER(CAST(2 AS FLOAT), -52)) * POWER(CAST(2 AS FLOAT),((CAST(CONVERT(VARBINARY(8000),Reverse(hex_Value)) AS BIGINT) & 0x7ff0000000000000) / EXP(52 * LOG(2))-1023))),53,LEN(hex_Value)))) --- FLOAT
WHEN system_type_id =59 THEN Left(LTRIM(STR(CAST(SIGN(CAST(Convert(VARBINARY(8000),REVERSE(hex_Value)) AS BIGINT))* (1.0 + (CAST(CONVERT(VARBINARY(8000),Reverse(hex_Value)) AS BIGINT) & 0x007FFFFF) * POWER(CAST(2 AS Real), -23)) * POWER(CAST(2 AS Real),(((CAST(CONVERT(VARBINARY(8000),Reverse(hex_Value)) AS INT) )& 0x7f800000)/ EXP(23 * LOG(2))-127))AS REAL),23,23)),8) --Real
WHEN system_type_id In (165,173) THEN (CASE WHEN CHARINDEX(0x,cast('' AS XML).value('xs:hexBinary(sql:column("hex_Value"))', 'VARBINARY(8000)')) = 0 THEN '0x' ELSE '' END) +cast('' AS XML).value('xs:hexBinary(sql:column("hex_Value"))', 'varchar(max)') -- BINARY,VARBINARY
WHEN system_type_id =36 THEN CONVERT(VARCHAR(MAX),CONVERT(UNIQUEIDENTIFIER,hex_Value)) --UNIQUEIDENTIFIER
END AS [FieldValue]
,NULL AS [FieldSetValue]
,[Rowlogcontents]
,[TransactionID]
,[Slot ID]
,[ID]
,[nullbit]
,[TRANSACTION ID]
,[Transaction Name]
,[Datum]
,[Current LSN]
,[Begin Time]
FROM CTE
ORDER BY [nullbit]

UPDATE #temp_Data SET [FieldSetValue] = --> New Column data
(CASE
-- VARCHAR; CHAR;
WHEN system_type_id In (167,175,189) THEN ISNULL('''' + [FieldValue] + '''','NULL')
-- NVARCHAR; NCHAR
WHEN system_type_id In (231,239) THEN ISNULL('N''' + [FieldValue] + '''','NULL')
-- SMALLDATETIME; DATE; DATETIME; UNIQUEIDENTIFIER
WHEN system_type_id In (58,40,61,36) THEN ISNULL('''' + [FieldValue] + '''','NULL')
-- TINYINT; SMALLINT; INT; REAL; MONEY; FLOAT; BIT; DECIMAL; NUMERIC; SMALLMONEY; BIGINT
WHEN system_type_id In (48,52,56,59,60,62,104,106,108,122,127) THEN ISNULL([FieldValue],'NULL')
END)
FROM sys.columns [D]
WHERE [object_id] = object_id(''+@SchemaName_n_TableName+'')
AND [Fieldname] = D.[name]

/*Create Update statement*/
/*Now we have the modified and actual data as well*/
/*We need to create the update statement in case of recovery*/

;With CTE AS
(SELECT
QUOTENAME([Name]) + '=' + ISNULL([A].[FieldSetValue],'NULL') + ' , ' AS [Field]
----(CASE
---- -- VARCHAR; CHAR;
---- WHEN system_type_id In (167,175,189) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' ,' + ' '
---- -- NVARCHAR; NCHAR
---- WHEN system_type_id In (231,239) THEN QUOTENAME([Name]) + '=' + ISNULL('N''' + [A].[FieldValue] + '''','NULL') + ' ,' + ''
---- -- SMALLDATETIME; DATE; DATETIME; UNIQUEIDENTIFIER
---- WHEN system_type_id In (58,40,61,36) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' ,' + ' '
---- -- TINYINT; SMALLINT; INT; REAL; MONEY; FLOAT; BIT; DECIMAL; NUMERIC; SMALLMONEY; BIGINT
---- WHEN system_type_id In (48,52,56,59,60,62,104,106,108,122,127) THEN QUOTENAME([Name]) + '=' + ISNULL([A].[FieldValue],'NULL') + ' ,' + ' '
---- END) AS [Field]
,A.[Slot ID]
,A.[TransactionID] AS [TransactionID]
,'D' AS [Type] --> Different
,[A].[Rowlogcontents]
,[A].[NonID]
,[A].[nullbit]
,[A].[TRANSACTION ID]
,[A].[Transaction Name]
,[A].[Datum]
,[A].[Current LSN]
,[A].[Begin Time]
FROM #temp_Data AS [A]
INNER JOIN #temp_Data AS [B] ON
[A].[FieldName]=[B].[FieldName]
AND [A].[Slot ID]=[B].[Slot ID]
--And [A].[TransactionID]=[B].[TransactionID]+1
AND [A].[TRANSACTION ID]=[B].[TRANSACTION ID] --> new condition
AND [A].[TransactionID]<>[B].[TransactionID] --> new condition
----AND [B].[TransactionID] =
---- (SELECT Min(Cast([TransactionID] AS INT)) AS [TransactionID]
---- FROM #temp_Data AS [C]
---- WHERE [A].[Slot ID]=[C].[Slot ID]
---- GROUP BY [Slot ID]
---- )
INNER JOIN sys.columns [D] ON [object_id] = object_id(''+@SchemaName_n_TableName+'')
AND A.[Fieldname] = D.[name]
WHERE ISNULL([A].[FieldValue],'') <> ISNULL([B].[FieldValue],'')

UNION ALL

SELECT
QUOTENAME([Name]) + '=' + ISNULL([A].[FieldSetValue],'NULL') + ' AND' AS [Field]
----(CASE
---- WHEN system_type_id In (167,175,189) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (231,239) THEN QUOTENAME([Name]) + '='+ ISNULL('N''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (58,40,61,36) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (48,52,56,59,60,62,104,106,108,122,127) THEN QUOTENAME([Name]) + '=' + ISNULL([A].[FieldValue],'NULL') + ' AND'
---- END) AS [Field]
,A.[Slot ID]
,A.[TransactionID] AS [TransactionID]
,'S' AS [Type] --> Same
,[A].[Rowlogcontents]
,[A].[NonID]
,[A].[nullbit]
,[A].[TRANSACTION ID]
,[A].[Transaction Name]
,[A].[Datum]
,[A].[Current LSN]
,[A].[Begin Time]
FROM #temp_Data AS [A]
INNER JOIN #temp_Data AS [B] ON [A].[FieldName] = [B].[FieldName]
AND [A].[Slot ID] = [B].[Slot ID]
--AND [A].[TransactionID] = [B].[TransactionID]+1
AND [A].[TRANSACTION ID]=[B].[TRANSACTION ID] --> new condition
AND [A].[TransactionID]<>[B].[TransactionID] --> new condition
----AND [B].[TransactionID] =
---- (SELECT MIN(CAST([TransactionID] AS INT)) AS [TransactionID]
---- FROM #temp_Data AS [C]
---- WHERE [A].[Slot ID]=[C].[Slot ID]
---- GROUP BY [Slot ID]
---- )
INNER JOIN sys.columns [D] ON [object_id] = object_id('' + @SchemaName_n_TableName + '')
AND [A].[Fieldname] = D.[name]
WHERE ISNULL([A].[FieldValue],'') = ISNULL([B].[FieldValue],'')
----AND A.[TransactionID] NOT IN
---- (SELECT MIN(CAST([TransactionID] AS INT)) AS [TransactionID]
---- FROM #temp_Data AS [C]
---- WHERE [A].[Slot ID]=[C].[Slot ID]
---- GROUP BY [Slot ID]
---- )

UNION ALL --> new

SELECT --> new
QUOTENAME([Name]) + '=' + ISNULL([A].[FieldSetValue],'NULL') + ' AND' AS [Field]
----(CASE
---- WHEN system_type_id In (167,175,189) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (231,239) THEN QUOTENAME([Name]) + '=' + ISNULL('N''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (58,40,61,36) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (48,52,56,59,60,62,104,106,108,122,127) THEN QUOTENAME([Name]) + '=' + ISNULL([A].[FieldValue],'NULL') + ' AND'
---- END) AS [Field]
,A.[Slot ID]
,A.[TransactionID] AS [TransactionID]
,CASE WHEN ([A].[Transaction Name] = 'INSERT') THEN 'N' ELSE 'O' END AS [Type] --> New or Old
,[A].[Rowlogcontents]
,[A].[NonID]
,[A].[nullbit]
,[A].[TRANSACTION ID]
,[A].[Transaction Name]
,[A].[Datum]
,[A].[Current LSN]
,[A].[Begin Time]
FROM #temp_Data AS [A]
INNER JOIN #temp_Data AS [B] ON
[A].[FieldName]=[B].[FieldName]
AND [A].[Slot ID]=[B].[Slot ID]
AND [A].[Transaction Name] IN ('INSERT','DELETE')
AND [A].[TransactionID]=[B].[TransactionID] --> self
INNER JOIN sys.columns [D] ON [object_id] = object_id(''+@SchemaName_n_TableName+'')
AND A.[Fieldname] = D.[name]
)

,CTEUpdateQuery AS
(SELECT
CASE A.[Transaction Name]
WHEN 'UPDATE' THEN
'UPDATE [' + @SchemaName_n_TableName + '] SET ' +
LEFT(STUFF(
(SELECT ' ' + ISNULL([Field],'')
FROM CTE B
WHERE A.[Slot ID]=B.[Slot ID] AND A.[TransactionID]=B.[TransactionID] AND B.[Type]='D' FOR XML PATH('')
),1,1,''), LEN(STUFF(
(SELECT ' ' + ISNULL([Field],'')
FROM CTE B
WHERE A.[Slot ID]=B.[Slot ID] AND A.[TransactionID]=B.[TransactionID] AND B.[Type]='D' FOR XML PATH('')
),1,1,'') )-2 --> -2 removes the final ', '
) +

' WHERE ' +

LEFT(STUFF(
(SELECT ' ' + ISNULL([Field],'') + ' '
FROM CTE C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Type]='S' FOR XML PATH('')
),1,1,'') ,LEN(STUFF(
(SELECT ' ' + ISNULL([Field],'') + ' '
FROM CTE C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Type]='S' FOR XML PATH('')
),1,1,'') )-4 --> -4 removes the final ' AND'
)
WHEN 'DELETE' THEN
'INSERT INTO [' + @SchemaName_n_TableName + '] (' +
LEFT(STUFF(
(SELECT ' [' + ISNULL([FieldName] + '],','')
FROM #temp_Data C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Rowlogcontents] IS NOT NULL FOR XML PATH('')
),1,1,'') ,LEN(STUFF(
(SELECT ' [' + ISNULL([FieldName] + '],','')
FROM #temp_Data C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Rowlogcontents] IS NOT NULL FOR XML PATH('')
),1,1,'') )-1 --> -1 removes the final ','
) + ') VALUES (' +
LEFT(STUFF(
(SELECT ' ' + ISNULL([FieldSetValue] + ',','')
FROM #temp_Data C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Rowlogcontents] IS NOT NULL FOR XML PATH('')
),1,1,'') ,LEN(STUFF(
(SELECT ' ' + ISNULL([FieldSetValue] + ',','')
FROM #temp_Data C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Rowlogcontents] IS NOT NULL FOR XML PATH('')
),1,1,'') )-1 --> -1 removes the final ','
) + ')'
WHEN 'INSERT' THEN
'DELETE FROM [' + @SchemaName_n_TableName + '] WHERE ' +
LEFT(STUFF(
(SELECT ' ' + ISNULL([Field],'')
FROM CTE C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Type]='N' FOR XML PATH('')
),1,1,'') ,LEN(STUFF(
(SELECT ' ' + ISNULL([Field],'')
FROM CTE C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Type]='N' FOR XML PATH('')
),1,1,'') )-4 --> -4 removes the final ' AND'
)
END AS [Update Statement]
,[Slot ID]
,[TransactionID]
,[Rowlogcontents]
,[A].[NonID]
,MAX([A].[nullbit])+1 AS [nullbit]
,[A].[TRANSACTION ID]
,[A].[Transaction Name]
,[A].[Datum]
,[A].[Current LSN]
,[A].[Begin Time]
FROM CTE A
GROUP BY [Slot ID]
,[TransactionID]
,[Rowlogcontents]
,[A].[NonID]
,[A].[TRANSACTION ID]
,[A].[Transaction Name]
,[A].[Begin Time]
,[A].[Current LSN]
,[A].[Datum]
)

INSERT INTO #temp_Data
SELECT 'Update Statement',ISNULL([Update Statement],''),NULL,NULL,[TransactionID],[Slot ID],[NonID],[nullbit],[TRANSACTION ID],[Transaction Name],[Datum],[Current LSN],[Begin Time]
FROM CTEUpdateQuery

/****************************************/
IF (@Debug > 0) BEGIN
print 'select * from CTE1'
select 'CTE1'
select * from (
/*This part is for variable data columns*/
SELECT
A.[ID]
,[Rowlogcontents]
,[TransactionID]
,[Slot ID]
,[TRANSACTION ID]
,[Transaction Name]
,[Datum]
,[Current LSN]
,[Begin Time]
,[NAME]
,cols.leaf_null_bit AS nullbit
,leaf_offset
,ISNULL(syscolumns.length, cols.max_length) AS [length]
,cols.system_type_id
,cols.leaf_bit_position AS bitpos
,ISNULL(syscolumns.xprec, cols.precision) AS xprec
,ISNULL(syscolumns.xscale, cols.scale) AS xscale
,SUBSTRING([nullBitMap], cols.leaf_null_bit, 1) AS is_null
--Calculate the variable column size from the variable column offset array
,(CASE WHEN leaf_offset<1 AND SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0
THEN CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*(leaf_offset*-1))-1, 2))))
ELSE 0 END
) AS [Column value Size]

--Calculate the column length
,(CASE WHEN leaf_offset<1 AND SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0
THEN CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING ([ColumnOffsetArray], (2*(leaf_offset*-1))-1, 2))))
- ISNULL(NULLIF(CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE (SUBSTRING([ColumnOffsetArray], (2*((leaf_offset*-1)-1))-1, 2)))), 0), [varColumnStart]) --> If Null OR zero
ELSE 0 END
) AS [Column Length]

--Get the Hexa decimal value from the RowlogContent
--HexValue of the variable column=Substring([Column value Size] - [Column Length] + 1,[Column Length])
--This is the data of your column but in the Hexvalue
,CASE WHEN SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=1
THEN NULL
ELSE SUBSTRING(Rowlogcontents,
(
(CASE WHEN leaf_offset<1 AND SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0
THEN CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*(leaf_offset*-1))-1, 2))))
ELSE 0 END
)
-(
(CASE WHEN leaf_offset<1 AND SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0
THEN CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*(leaf_offset*-1))-1, 2))))
- ISNULL(NULLIF(CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*((leaf_offset*-1)-1))-1, 2)))), 0), [varColumnStart]) --> If Null OR zero
ELSE 0 END
))
)+1,(
(CASE WHEN leaf_offset<1 AND SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0
THEN CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*(leaf_offset*-1))-1, 2))))
- ISNULL(NULLIF(CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([ColumnOffsetArray], (2*((leaf_offset*-1)-1))-1, 2)))), 0), [varColumnStart]) --> If Null OR zero
ELSE 0 END
))
)
END AS hex_Value

FROM @DeletedRecords A
INNER JOIN sys.allocation_units allocunits ON
A.[AllocUnitId]=allocunits.[Allocation_Unit_Id]
INNER JOIN sys.partitions partitions ON
(allocunits.type IN (1, 3) AND partitions.hobt_id = allocunits.container_id)
OR (allocunits.type = 2 AND partitions.partition_id = allocunits.container_id)
INNER JOIN sys.system_internals_partition_columns cols ON cols.partition_id = partitions.partition_id
LEFT OUTER JOIN syscolumns ON syscolumns.id = partitions.object_id AND syscolumns.colid = cols.partition_column_id
WHERE leaf_offset < 0

UNION
/*This part is for fixed data columns*/
SELECT
A.[ID]
,[Rowlogcontents]
,[TransactionID]
,[Slot ID]
,[TRANSACTION ID]
,[Transaction Name]
,[Datum]
,[Current LSN]
,[Begin Time]
,[NAME]
,cols.leaf_null_bit AS [nullbit]
,leaf_offset
,ISNULL(syscolumns.length, cols.max_length) AS [length]
,cols.system_type_id
,cols.leaf_bit_position AS bitpos
,ISNULL(syscolumns.xprec, cols.precision) AS xprec
,ISNULL(syscolumns.xscale, cols.scale) AS xscale
,SUBSTRING([nullBitMap], cols.leaf_null_bit, 1) AS is_null
,(SELECT TOP 1 ISNULL(SUM(CASE WHEN C.leaf_offset >1 THEN max_length ELSE 0 END),0)
FROM sys.system_internals_partition_columns C
WHERE cols.partition_id=C.partition_id AND C.leaf_null_bit<cols.leaf_null_bit
)+5 AS [Column value Size]
,syscolumns.length AS [Column Length]

,CASE WHEN SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=1
THEN NULL
ELSE SUBSTRING(Rowlogcontents,
(SELECT TOP 1 ISNULL(SUM(CASE WHEN C.leaf_offset >1 THEN max_length ELSE 0 END),0)
FROM sys.system_internals_partition_columns C
WHERE cols.partition_id =C.partition_id AND C.leaf_null_bit<cols.leaf_null_bit
)+5
,syscolumns.length)
END AS hex_Value
FROM @DeletedRecords A
INNER JOIN sys.allocation_units allocunits ON A.[AllocUnitId]=allocunits.[Allocation_Unit_Id]
INNER JOIN sys.partitions partitions ON
(allocunits.type IN (1, 3) AND partitions.hobt_id = allocunits.container_id)
OR (allocunits.type = 2 AND partitions.partition_id = allocunits.container_id)
INNER JOIN sys.system_internals_partition_columns cols ON cols.partition_id = partitions.partition_id
LEFT OUTER JOIN syscolumns ON syscolumns.id = partitions.object_id AND syscolumns.colid = cols.partition_column_id
WHERE leaf_offset>0
) AS t1
order by [Begin Time],[ID],[nullbit]

print 'select * from CTE2'
select 'CTE2'
select * into #CTE from (
SELECT
QUOTENAME([Name]) + '=' + ISNULL([A].[FieldSetValue],'NULL') + ' , ' AS [Field]
----(CASE
---- -- VARCHAR; CHAR;
---- WHEN system_type_id In (167,175,189) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' ,' + ' '
---- -- NVARCHAR; NCHAR
---- WHEN system_type_id In (231,239) THEN QUOTENAME([Name]) + '=' + ISNULL('N''' + [A].[FieldValue] + '''','NULL') + ' ,' + ''
---- -- SMALLDATETIME; DATE; DATETIME; UNIQUEIDENTIFIER
---- WHEN system_type_id In (58,40,61,36) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' ,' + ' '
---- -- TINYINT; SMALLINT; INT; REAL; MONEY; FLOAT; BIT; DECIMAL; NUMERIC; SMALLMONEY; BIGINT
---- WHEN system_type_id In (48,52,56,59,60,62,104,106,108,122,127) THEN QUOTENAME([Name]) + '=' + ISNULL([A].[FieldValue],'NULL') + ' ,' + ' '
---- END) AS [Field]
,A.[Slot ID]
,A.[TransactionID] AS [TransactionID]
,'D' AS [Type] --> Different
,[A].[Rowlogcontents]
,[A].[NonID]
,[A].[nullbit]
,[A].[TRANSACTION ID]
,[A].[Transaction Name]
,[A].[Datum]
,[A].[Current LSN]
,[A].[Begin Time]
FROM #temp_Data AS [A]
INNER JOIN #temp_Data AS [B] ON
[A].[FieldName]=[B].[FieldName]
AND [A].[Slot ID]=[B].[Slot ID]
--And [A].[TransactionID]=[B].[TransactionID]+1
AND [A].[TRANSACTION ID]=[B].[TRANSACTION ID] --> new condition
AND [A].[TransactionID]<>[B].[TransactionID] --> new condition
AND [A].[Current LSN]=[B].[Current LSN] --> new condition
----AND [B].[TransactionID] =
---- (SELECT Min(Cast([TransactionID] AS INT)) AS [TransactionID]
---- FROM #temp_Data AS [C]
---- WHERE [A].[Slot ID]=[C].[Slot ID]
---- GROUP BY [Slot ID]
---- )
INNER JOIN sys.columns [D] ON [object_id] = object_id(''+@SchemaName_n_TableName+'')
AND A.[Fieldname] = D.[name]
WHERE ISNULL([A].[FieldValue],'') <> ISNULL([B].[FieldValue],'')

UNION ALL

SELECT
QUOTENAME([Name]) + '=' + ISNULL([A].[FieldSetValue],'NULL') + ' AND' AS [Field]
----(CASE
---- WHEN system_type_id In (167,175,189) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (231,239) THEN QUOTENAME([Name]) + '='+ ISNULL('N''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (58,40,61,36) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (48,52,56,59,60,62,104,106,108,122,127) THEN QUOTENAME([Name]) + '=' + ISNULL([A].[FieldValue],'NULL') + ' AND'
---- END) AS [Field]
,A.[Slot ID]
,A.[TransactionID] AS [TransactionID]
,'S' AS [Type] --> Same
,[A].[Rowlogcontents]
,[A].[NonID]
,[A].[nullbit]
,[A].[TRANSACTION ID]
,[A].[Transaction Name]
,[A].[Datum]
,[A].[Current LSN]
,[A].[Begin Time]
FROM #temp_Data AS [A]
INNER JOIN #temp_Data AS [B] ON [A].[FieldName] = [B].[FieldName]
AND [A].[Slot ID] = [B].[Slot ID]
--AND [A].[TransactionID] = [B].[TransactionID]+1
AND [A].[TRANSACTION ID]=[B].[TRANSACTION ID] --> new condition
AND [A].[TransactionID]<>[B].[TransactionID] --> new condition
AND [A].[Current LSN]=[B].[Current LSN] --> new condition
----AND [B].[TransactionID] =
---- (SELECT MIN(CAST([TransactionID] AS INT)) AS [TransactionID]
---- FROM #temp_Data AS [C]
---- WHERE [A].[Slot ID]=[C].[Slot ID]
---- GROUP BY [Slot ID]
---- )
INNER JOIN sys.columns [D] ON [object_id] = object_id('' + @SchemaName_n_TableName + '')
AND [A].[Fieldname] = D.[name]
WHERE ISNULL([A].[FieldValue],'') = ISNULL([B].[FieldValue],'')
----AND A.[TransactionID] NOT IN
---- (SELECT MIN(CAST([TransactionID] AS INT)) AS [TransactionID]
---- FROM #temp_Data AS [C]
---- WHERE [A].[Slot ID]=[C].[Slot ID]
---- GROUP BY [Slot ID]
---- )

UNION ALL --> new

SELECT --> new
QUOTENAME([Name]) + '=' + ISNULL([A].[FieldSetValue],'NULL') + ' AND' AS [Field]
----(CASE
---- WHEN system_type_id In (167,175,189) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (231,239) THEN QUOTENAME([Name]) + '=' + ISNULL('N''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (58,40,61,36) THEN QUOTENAME([Name]) + '=' + ISNULL('''' + [A].[FieldValue] + '''','NULL') + ' AND'
---- WHEN system_type_id In (48,52,56,59,60,62,104,106,108,122,127) THEN QUOTENAME([Name]) + '=' + ISNULL([A].[FieldValue],'NULL') + ' AND'
---- END) AS [Field]
,A.[Slot ID]
,A.[TransactionID] AS [TransactionID]
,CASE WHEN ([A].[Transaction Name] = 'INSERT') THEN 'N' ELSE 'O' END AS [Type] --> New or Old
,[A].[Rowlogcontents]
,[A].[NonID]
,[A].[nullbit]
,[A].[TRANSACTION ID]
,[A].[Transaction Name]
,[A].[Datum]
,[A].[Current LSN]
,[A].[Begin Time]
FROM #temp_Data AS [A]
INNER JOIN #temp_Data AS [B] ON
[A].[FieldName]=[B].[FieldName]
AND [A].[Slot ID]=[B].[Slot ID]
AND [A].[Transaction Name] IN ('INSERT','DELETE')
AND [A].[TransactionID]=[B].[TransactionID] --> self
INNER JOIN sys.columns [D] ON [object_id] = object_id(''+@SchemaName_n_TableName+'')
AND A.[Fieldname] = D.[name]
) as t2
select * from #CTE
order by [Begin Time],[Slot ID],[NonID],[nullbit]

print 'select * from CTEUpdateQuery'
select 'CTEUpdateQuery'
SELECT
CASE A.[Transaction Name]
WHEN 'UPDATE' THEN
'UPDATE [' + @SchemaName_n_TableName + '] SET ' +
LEFT(STUFF(
(SELECT ' ' + ISNULL([Field],'')
FROM #CTE B
WHERE A.[Slot ID]=B.[Slot ID] AND A.[TransactionID]=B.[TransactionID] AND B.[Type]='D' FOR XML PATH('')
),1,1,''), LEN(STUFF(
(SELECT ' ' + ISNULL([Field],'')
FROM #CTE B
WHERE A.[Slot ID]=B.[Slot ID] AND A.[TransactionID]=B.[TransactionID] AND B.[Type]='D' FOR XML PATH('')
),1,1,'') )-2 --> -2 removes the final ', '
) +

' WHERE ' +

LEFT(STUFF(
(SELECT ' ' + ISNULL([Field],'') + ' '
FROM #CTE C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Type]='S' FOR XML PATH('')
),1,1,'') ,LEN(STUFF(
(SELECT ' ' + ISNULL([Field],'') + ' '
FROM #CTE C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Type]='S' FOR XML PATH('')
),1,1,'') )-4 --> -4 removes the final ' AND'
)
WHEN 'DELETE' THEN
'INSERT INTO [' + @SchemaName_n_TableName + '] (' +
LEFT(STUFF(
(SELECT ' [' + ISNULL([FieldName] + '],','')
FROM #temp_Data C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Rowlogcontents] IS NOT NULL FOR XML PATH('')
),1,1,'') ,LEN(STUFF(
(SELECT ' [' + ISNULL([FieldName] + '],','')
FROM #temp_Data C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Rowlogcontents] IS NOT NULL FOR XML PATH('')
),1,1,'') )-1 --> -1 removes the final ','
) + ') VALUES (' +
LEFT(STUFF(
(SELECT ' ' + ISNULL([FieldSetValue] + ',','')
FROM #temp_Data C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Rowlogcontents] IS NOT NULL FOR XML PATH('')
),1,1,'') ,LEN(STUFF(
(SELECT ' ' + ISNULL([FieldSetValue] + ',','')
FROM #temp_Data C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Rowlogcontents] IS NOT NULL FOR XML PATH('')
),1,1,'') )-1 --> -1 removes the final ','
) + ')'
WHEN 'INSERT' THEN
'DELETE FROM [' + @SchemaName_n_TableName + '] WHERE ' +
LEFT(STUFF(
(SELECT ' ' + ISNULL([Field],'')
FROM #CTE C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Type]='N' FOR XML PATH('')
),1,1,'') ,LEN(STUFF(
(SELECT ' ' + ISNULL([Field],'')
FROM #CTE C
WHERE A.[Slot ID]=C.[Slot ID] AND A.[TransactionID]=C.[TransactionID] AND C.[Type]='N' FOR XML PATH('')
),1,1,'') )-4 --> -4 removes the final ' AND'
)
END AS [Update Statement]
,[Slot ID]
,[TransactionID]
,[Rowlogcontents]
,[A].[NonID]
,MAX([A].[nullbit])+1 AS [nullbit]
,[A].[TRANSACTION ID]
,[A].[Transaction Name]
,[A].[Datum]
,[A].[Current LSN]
,[A].[Begin Time]
FROM #CTE A
GROUP BY [Slot ID]
,[TransactionID]
,[Rowlogcontents]
,[A].[NonID]
,[A].[TRANSACTION ID]
,[A].[Transaction Name]
,[A].[Begin Time]
,[A].[Current LSN]
,[A].[Datum]
drop table #CTE
END

IF (@Debug > 0) BEGIN
print 'select * from temp_Data1'
select '#temp_Data1'
select * from #temp_Data order by [TransactionID],[nullbit]
END

--Create the column name in the same order to do pivot table.
DECLARE @FieldNames VARCHAR(MAX)
SET @FieldNames = STUFF(
(SELECT ','+CAST(QUOTENAME([Name]) AS VARCHAR(MAX))
FROM syscolumns
WHERE id = object_id(''+@SchemaName_n_TableName+'') FOR XML PATH('')
),1,1,'')

--Finally, pivot table and get the change history so one can get the data back.
--The [Update Statement] column will give you the query that you can execute for recovery.
-- NOTE: Need a placeholder type for [Execution Account] (else it will be int)
SET @sql = 'SELECT ROW_NUMBER() OVER (ORDER BY [LSN],[Datum] DESC) AS [RowNo],' + @FieldNames
+ ',[Datum],[Update Statement],[Transaction],-1 AS [Prev RowNo],[Date],[Execution Account],[TRANSACTION ID],[Slot ID],[LSN] '
+ 'INTO [@ResultTable] '
+ 'FROM (SELECT [FieldName],[FieldValue],[Transaction Name] AS [Transaction],[Datum] AS [Datum],[Begin Time] AS [Date]'
+',[TRANSACTION ID] AS [Execution Account],[TRANSACTION ID],[Slot ID],[Current LSN] AS [LSN] FROM #temp_Data) AS src '
+ 'PIVOT (Min([FieldValue]) FOR [FieldName] IN (' + @FieldNames + ',[Update Statement])) AS pvt '
+ 'ORDER BY [LSN],[Datum] DESC'

--> Create a table to hold the dynamic SQL results --> doesn't seem to work
DECLARE @sql1 VARCHAR(MAX)
SET @sql1 = 'Declare @result Table ([RecNo] INT NOT NULL IDENTITY(1,1) PRIMARY KEY,' + REPLACE(@FieldNames,',',' varchar(max),') + 'varchar(max),'
+ '[Datum] varchar(20),[Update Statement] varchar(max),[TRANSACTION ID] varchar(max),[Transaction] varchar(max)'
+',[Slot ID] int,[LSN] varchar(max),[Prev RowNo] int,[Date] varchar(20))'
--EXEC(@sql1)

EXEC sp_executesql @sql
IF OBJECT_ID (N'[@ResultTable]', N'U') IS NOT NULL
BEGIN
UPDATE [@ResultTable] SET [Prev RowNo] =
ISNULL((SELECT MAX(B.[RowNo]) AS [ID] FROM [@ResultTable] B
WHERE B.[Slot ID] = A.[Slot ID] AND B.[RowNo] < A.[RowNo]),0)
FROM [@ResultTable] A
UPDATE [@ResultTable] SET [Execution Account] =
(SELECT [Transaction Account] FROM #TransIdAllList B WHERE B.[Transaction ID] = A.[Transaction ID])
FROM [@ResultTable] A
SELECT * FROM [@ResultTable]
DROP TABLE [@ResultTable]
END

IF (@Debug > 0) BEGIN
print @FieldNames
print @sql1
print ''
print @sql
END

GO --> required for testing/debugging (dumps all local entities from above)
SET NOEXEC OFF

PS: Não entendeu nada ?!?? Blz… isso não é para os fracos… 😉

Usar o xp_logininfo


Em alguns casos nos deparamos com logins estranhos nos servidores SQL.

Uma coisa que deixa qualquer DBA feliz da vida (#SQN) é encontrar um grupo de Windows dentro com permissões dentro do SQL, mais sexy ainda quando esse grupo esta na role de SysAdmin…

Em todo o caso, o DBA nem sempre tem acesso a administração do AD para saber quem, quantos, quais, porque, são os usuários do grupo do Windows e tem que perguntar para alguém de administração do SO para ter esta informação.

O que nem todo DBA sabe, é que existe uma Stored Procedure, que vem desde o SQL 2000, pode ajudar a descobrir esta informação…

Ex. 1 Todos os usuários de um grupo:


EXEC xp_logininfo 'BUILTIN\Administrators', 'members'

Ex. 2 Quais grupos o usuário faz parte:


EXEC xp_logininfo 'Domain\User', 'all'

Challenge Accepted and Now Completed !!!


Vocês conhecem a expressão: “Mais feliz que pinto no lixo”? ou “Mais feliz que filho de barbeiro em quermesse”?

hoje recebi o seguinte email do pessoal da Microsoft:

MASTER

SIM !!! Depois de passar por todo o calvário desde o treinamento,,, ir algumas vezes até os EUA para fazer o exame teórico… consegui passar nas provas necessárias para a certificação…

Oficialmente….

achievement_unlocked1

20131119_170628

20131119_171016

e agora com o direito de ter um post no The Master Blog

Atualização !!!

E agora no link do Meet the Masters tem meu nome

Demorou mas agora ta no Transcript:

master

 

SQL Saturday #245 – Rio de Janeiro


Teremos um grande evento da comunidade SQL no Brasil…. o SQL Saturday #245

O SQL Saturday é totalmente gratuito e focado em SQL Server, um dia inteiro de palestras técnicas. No momento o evento encontra-se com o Call for Speakers aberto, ou seja, recebendo inúmeras propostas de palestras, tendo até agora já recebido propostas de palestrantes de vários locais do Brasil e inclusive de outros países !!!

Trata-se da 2a edição do evento, que ocorreu com muito sucesso em abril de 2012, contando na época com mais de 300 participantes.

SQL Saturday é uma marca de eventos já conhecida mundialmente pela alta qualidade técnica. A marca pertence a uma organização chamada SQL PASS, cujo trabalho envolve apoiar grupos de usuários de SQL Server – denominados de PASS Chapter – por todo o mundo.

O SQL PASS cede a marca, bem como algumas ferramentas on-line, patrocinio e orientação para que o PASS Chapter da região realize o evento. No Rio de Janeiro o evento está sendo realizado pelo PASS Chapter devSQL, o mais antigo PASS Chapter do Brasil, liderado por Dennes Torres (t | b).

As inscrições para o evento estão abertas e, como citado antes, é totalmente gratuito. Trata-se do 2o evento realizado no Brasil. O primeiro, realizado em São Paulo por outro PASS Chapter, ficou totalmente lotado antes mesmo da grade de palestras ser definida.

Evento : SQL Saturday #245 – Rio de Janeiro

Data : 31/08

Horário : Abertura as 08:00hs, inicio das palestras as 09:00hs até as 18hs

Local : Universidade Veiga de Almeida

Endereço : Rua Ibituruna, 108, tijuca, próximo a estação São Cristóvão do metrô

Site do Evento : http://www.sqlsaturday.com/245/eventhome.aspx

SQLPASS – Keynote D2


08h10 – Hoje é o kilt day,,,,

08h18 – Hoje tem um monte de agradecimento para as pessoas que ajudam o evento a ser realizado

08h25 – O Pessoal apresentou um vídeo sobre as qualidades mais interessante para as pessoas sobre o sql,,, muitas das pessoas são de instituições bancárias,,,,

08h30 – O VP está falando sobre as novidades do SQL Server 2012, começou falando sobre as novidades de alta disponibilidade, que por sinal realmente é bem interessante

Agora o VP da MSC está falando sobre a utilização deles do SQL, comentando a necessidades deles de nunca poder parar de acessar os dados.

08h40 – O pessoal esta mostrando como configurar o modo Always-On do SQL 2012,,, isso é simplesmente muito bom,,,,

08h53 – Até que enfim alguém está fazendo exemplos sem usar Excel,,, e pra ajudar a mina vira e manda uma: “Da pra fazer pelo GUI, mas sou da velha guarda, então olhem o código aqui,,,”

09h00 – Agora vamos ver o appliance com SQL,,, um hardware tunado para rodar banco,,,, só banco,,,, e mais nada além de banco,,,, isso é um sonho? SQL Server Parallel Data warehouse,,,, agora não é só HP,,, a DELL também tem hardware pra isso,,, é uma pena que isso, se um dia chegar ao Brasil, vai ser muito caro,,,,

09h16 – Anuncio do driver de ODBC para linux,,,, já que tem um monte de gente desenvolvendo para linux, pelo menos acessem uma base decente sem usar a droga do jdbc,,,

09h30 – trouxemos a chuva para Seattle,,, afinal,,, muito SQL Azure  da nisso,,,,

09h40 – O pessoal anunciou que o SQL Azure vai aceitar bases até 150gb,,, e em qualquer collation,,, vamos ver se ele começa a fazer alguma sombra no Brasil,,,

SQLPASS – Chegamos no esquema


11/10/11 – Fizemos o checkin do evento,,, como começo a ficar de costume, nos meus brindes veio faltando alguma coisa,,, no voo foi o fone de ouvido,,, daqui foi a cordinha para o crachá.

12/10/11 – Chegamos no evento,,, um monte de gente,,, já na escada rolante escuramos alguns brasileiros,,,

08h13 – muita gente no salão para o keynote,,, esse pessoal é muito estranho,,, só sabem falar inglês,,, q coisa chata,,, uahuahauhauha e nada de começar….

08h17 – começa com um video de pessoas falando sobre o significado do evento,,,

08h19 – apareceu o presidente do SQLPASS (Rushabh Mehta),,, ele está falando sobre a comunidade,,, mostrando quem faz parte do border,,, ele disse que o twitter está acima da capacidade,,, alguém precisa dizer pra ele que o wireless daqui não está aguentando a quantidade de gente,,,

08h27 – 189 seções, 204 palestrantes,,, e muita gente,,, no folheto dentro da mala mostra onde estão as salas interessantes,,, e qual o nível do treinamento,,,,

08h36 – basicamente uma explicação do evento,,, até que foi legal…

08h37 – Agora o Sr. vice presidente de produtos MS, Ted Kummert,,,

08h39 – The New World of Data, Ted Kummert está falando sobre que a menina dos olhos é Cloud,,, até aí,,, qual a novidade?,,

08h42 – 400k horas, 79k membros, 300 mvps,,, é coisa de gente grande,,,,

08h45 – Ted Kummert, está falando sobre os 3 pilares do SQL Server Denali.

08h50 – Agora o SQL Server Denali tem um nome oficial,,, SQL Server 2012 (esse pessoal é muito criativo,,,) e pelo que ele disse vai ser lançado no começo do ano que vem (isso vai ser uma grande novidade)

08h57 – Vamos ter outra versão do Azure até o final do ano,,, com novos tipos de dados….

09h07 – Denny Lee está demonstrando algumas novas consultas usando como exemplo o excel…

09h13 – Agora tem um pouco de SQL Azure labs…. vamos ver que zona vai sair disso,,,

09h18 – Mais exemplos com excel,,,, nós já sabemos que podemos extrair muitos dados, gerar relatórios e fazer uma festa com o excel acessando SQL,,, mas poxa, não viemos até aqui pra brincar com Excel,,, quero ver SQL,,,

09h26 – Agora pra que estudar para BI? qualquer criança que conheça um pouquinho de excel vai conseguir fazer qualquer coisa com acesso aos dados,,, até que não é ruim,,, o problema é que essa liberdade para o usuário, que na maior parte das vezes toma piau pra conseguir mandar um email, pode gerar mais dificuldades do que facilidades… O usuário tem que aprender a saber o que quer antes de ter a liberdade de acessar o que ele quer,,,, sem treinamento isso pode se tornar mais em problema do que liberdade,,,

09h37 – Amir Nets faz umas apresentações muito boas…. as apresentações de BI dele são muito boas…

09h55 bem no final da apresentação do Amir Netz, o tablet não consegue conectar na internet,,, e para tora a apresentação,,, uhauhauhaua, vir em uma apresentação com produtos MS e ela não ter problema? não tem graça,,,

09h57 – fim do keynote,,, agora vamos ver as outras coisas,,,