If you've just implemented an autonumbering solution in CRM, newly created records will have an autonumber generated for them. Now, however, it's likely you'll need to backpopulate all records that were created before the autonumbering solution was implemented.

As an example, the SQL script below selects all Contacts in CRM and iterates through them, setting their [AutoNumber] field equal to the Contact's database row number. The script also pads this number, to keep in alignment with my autonumber syntax, which is padded to be a minimum of 10 characters long. For example, a row number of 489 is padded to an autonumber of 0000000489.

With UpdateData As
(
  SELECT ContactId, [AutoNumber], FullName, 
  RIGHT('0000000000'+CAST((ROW_NUMBER() OVER (ORDER BY CreatedOn DESC)) AS VARCHAR(10)),10) AS RN
  FROM [Database].[dbo].[ContactBase]
)
UPDATE [Database].dbo.ContactBase SET [AutoNumber] = RN
FROM [Database].dbo.ContactBase
INNER JOIN UpdateData ON [Database].dbo.ContactBase.ContactId = UpdateData.ContactId

When using this script, replace:

  • [AutoNumber] with the schema name of your autonumber field e.g. new_autonumber
  • [Database] with the name of your CRM database
  • [ContactBase] with the table of the entity you're looking to update. You'll also need to replace ContactId with the primary id of this entity

I recommend this autonumber from Celodon, the code for which is hosted here on GitHub.