sqlsql-serverhashbytes

Insert hashbytes Incorrect syntax near 'MD5'


I'm using SQL Server 2014. As part of a larger task, I need to detect updates etc from a table so am implementing Hashbytes. The Hasbytes field is defined as varbinary(MAX).

This is my SQL:

INSERT INTO tbl_People
  SELECT
    id,
    Name,
    Add1,
    Add2,
    Add3,
    HashValue as Hashbytes('MD5',CONCAT('|',Name, Add1, Add2, Add3))
from tbl_PeopleSource

However, I just keep receiving the error:

Incorrect syntax near 'MD5'.

Where am I going wrong?


Solution

  • Missing a comma just before the HashValue alias, to separate Add3 from the next column. Also the alias is inverted, should be <expression> as AliasName.

    Add3, -- Here comma
    Hashbytes('MD5',CONCAT('|',Name, Add1, Add2, Add3)) as HashValue -- Inverted alias
    

    Also it's good practice to list the inserted table's column so the order doesn't get wrongly interpreted:

    INSERT INTO tbl_People (
        ID,
        Name,
        Col1,
        Col2,
        Col3,
        HashValue)
    SELECT
        ...
    

    There are multiple ways to use column aliases on SQL Server.