Search code examples
sql-serverfunctionhashbytes

SQL Server HashBytes Function


Can someone please tell me why I'm getting different answers for the following:

Here is a very simple function used to return the hash Value:

CREATE Function [fn_GetPin](@strText VARCHAR(254))
RETURNS VARCHAR(254)
AS
BEGIN
    SET @strText = HashBytes('MD5', @strText);
    RETURN @strText;
END

Here is my SQL that returns 2 different values:

SELECT HashBytes('MD5', '7690') as Hash1
        , dbo.fn_GetPin('7690') AS Hash2

Results:

Hash1   Hash2
0xC6776F93BC9AFE2E511A1DBD5478362C  Æwo“¼šþ.Q½Tx6,

For some reason the function is not returning the same value as HASH1. I'm just not sure why.

Thanks.

UPDATE:

Accepted answer is below, I just added (max) to the VARBINARY to return the whole value. Thanks All.

CREATE Function [fn_GetPin](@strText VARCHAR(254))
RETURNS VARBINARY(max)
AS
BEGIN
    Return HashBytes('MD5', @strText);
END

Solution

  • CREATE Function [fn_GetPin](@strText VARCHAR(254))
    RETURNS VARBINARY
    AS
    BEGIN
        Return HashBytes('MD5', @strText);
    END
    

    function should return a varbinary value.