June 02, 2009

Generate a HASH value using SQL Server 2005/2008

Do you want to pass a string and generate a HASH value from it using SQL Server? Here’s a very simple way of doing so using HashBytes. Let us see this with an example:

DECLARE @SomeValue nvarchar(50);
SELECT @SomeValue = 'SQLServerCurry';
SELECT HashBytes('SHA1', @SomeValue);

generates an output


Using HashBytes, you can use algorithms like MD2, MD4, MD5, SHA or SHA1. The input string can be a varchar, nvarchar or varbinary and can be upto a maximum of 8000 bytes

About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal


jbtatro said...

the function only uses the first 30 characters of your string

jbtatro said...

sorry that was my fault, i did something like HASHBYTES('SHA1', cast( '...really large string' as nvarchar)) which when you don't specify a size it uses 30 so it was truncating its value, my bad