Skip to content

Instantly share code, notes, and snippets.

@nilsandrey
Last active July 11, 2023 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilsandrey/0f9c9aa2f6b1c7bb100e39a990840dde to your computer and use it in GitHub Desktop.
Save nilsandrey/0f9c9aa2f6b1c7bb100e39a990840dde to your computer and use it in GitHub Desktop.
Obtain an MD5 Checksum per table of all the rows content for all tables in a database.
DECLARE @table_name NVARCHAR(255);
DECLARE @sql NVARCHAR(MAX);
DECLARE @sep NVARCHAR(10);
DECLARE @md5_hash NVARCHAR(32);
DECLARE table_cursor CURSOR FOR
SELECT name FROM sys.tables;
OPEN table_cursor;
FETCH NEXT FROM table_cursor INTO @table_name;
SET @sql = '';
SET @sep = '';
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = @sql + @sep + 'SELECT '''+@table_name+''' as TableName, HASHBYTES(''MD5'', (SELECT * FROM ' + @table_name + ' FOR XML AUTO)) as md5hash';
SET @sep = ' UNION ';
FETCH NEXT FROM table_cursor INTO @table_name;
END
CLOSE table_cursor;
DEALLOCATE table_cursor;
EXEC sp_executesql @sql, N'@md5_hash NVARCHAR(32) OUTPUT', @md5_hash OUTPUT;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment