Search code examples
sql-serverauto-generate

Sql Server Column with Auto-Generated Data


I have a customer table, and my requirement is to add a new varchar column that automatically obtains a random unique value each time a new customer is created.

I thought of writing an SP that randomizes a string, then check and re-generate if the string already exists. But to integrate the SP into the customer record creation process would require transactional SQL stuff at code level, which I'd like to avoid.

Help please?

edit: I should've emphasized, the varchar has to be 5 characters long with numeric values between 1000 and 99999, and if the number is less than 10000, pad 0 on the left.


Solution

  • if it has to be varchar, you can cast a uniqueidentifier to varchar.

    to get a random uniqueidentifier do NewId()

    here's how you cast it:

    CAST(NewId() as varchar(36))
    

    EDIT

    as per your comment to @Brannon:

    are you saying you'll NEVER have over 99k records in the table? if so, just make your PK an identity column, seed it with 1000, and take care of "0" left padding in your business logic.