title: Generate a unique time-based id on a table in SQL Server
body: <p>I'm trying to generate a unique id/timestamp based on the clock of the database server. This is not the main Id of the table, but it's in my interest that this value is unique for each row. This code is in a stored procedure that will be executed simultaneously by various processes running at the same time.</p>
  
  <p>I've come up with this code but can't find a way to make it more elegant. As far as I've tested, the only way to make sure the other processes don't generate the same value on some other thread is by locking the table while doing a check exists.</p>
  
  <pre><code>DECLARE @CurrentRRN varchar(30)
  SET @CurrentRRN = FORMAT(SYSDATETIME(), 'yyyyMMddHHmmssffffff')
  
  IF(EXISTS(SELECT RRN FROM dbo.Numbering WITH (xlock, tablockx, holdlock) 
    WHERE RRN = @CurrentRRN)) BEGIN
  
    WHILE( EXISTS(SELECT RRN FROM dbo.Numbering WHERE RRN = @CurrentRRN) )
      BEGIN
          SET @CurrentRRN = FORMAT(SYSDATETIME(), 'yyyyMMddHHmmssffffff')
      END
  
  END
  
  INSERT INTO dbo.Numbering
  (RRN)
  Values
  (@CurrentRRN)
  
  print @CurrentRRN
  </code></pre>