Calculate Hash or Checksum for a table in SQL Server

Gabe Brown picture Gabe Brown · Oct 13, 2009 · Viewed 32.6k times · Source

I'm trying to compute a checksum or a hash for an entire table in SQL Server 2008. The problem I'm running into is that the table contains an XML column datatype, which cannot be used by checksum and has to be converted to nvarchar first. So I need to break it down into two problems:

  1. calculate a checksum for a row, schema is unknown before runtime.
  2. calculate the checksum for all of the rows to get the full table checksum.

Answer

Cade Roux picture Cade Roux · Oct 13, 2009

You can use CHECKSUM_AGG. It only takes a single argument, so you could do CHECKSUM_AGG(CHECKSUM(*)) - but this doesn't work for your XML datatype, so you'll have to resort to dynamic SQL.

You could generate dynamically the column list from INFORMATION_SCHEMA.COLUMNS and then insert int into a template:

DECLARE @schema_name NVARCHAR(MAX) = 'mySchemaName';
DECLARE @table_name NVARCHAR(MAX) = 'myTableName';
DECLARE @column_list NVARCHAR(MAX);

SELECT @column_list = COALESCE(@column_list + ', ', '')
        + /* Put your casting here from XML, text, etc columns */ QUOTENAME(COLUMN_NAME)
FROM    INFORMATION_SCHEMA.COLUMNS
WHERE   TABLE_NAME = @table_name
    AND TABLE_SCHEMA = @schema_name

DECLARE @template AS varchar(MAX)
SET @template = 'SELECT CHECKSUM_AGG(CHECKSUM({@column_list})) FROM {@schema_name}.{@table_name}'

DECLARE @sql AS varchar(MAX)
SET @sql = REPLACE(REPLACE(REPLACE(@template,
    '{@column_list}', @column_list),
    '{@schema_name}', @schema_name),
    '{@table_name}', @table_name)

EXEC ( @sql )