title: Create PK for #temp table failed when the script is run in parallel
body: <p>I have the following code in a stored procedure.</p>
  
  <pre class="lang-sql prettyprint-override"><code>....
  select ... into #temp from ....
  alter table #temp add constraint PK_mytemp13 primary key (....)
  ....
  </code></pre>
  
  <p>And I will get the following error message from time to time if the stored procedure is run in parallel. </p>
  
  <blockquote>
    <p>There is already an object named 'PK_perf322dsf' in the database.
    Could not create constraint. See previous errors.</p>
  </blockquote>
  
  <p>I think it can be avoid by the following approaches. Is there any other more elegant solution? </p>
  
  <ol>
  <li><p>Create a temp table with primary key first. Then insert the rows.<br>
  <code>create table #temp (... primary key (....))</code></p></li>
  <li><p>Create PK dynamically with session id dynamically.<br>
  <code>declare @s varchar(500) = 'alter table #temp add constraint PK_temp' + @@spid + ' primary key (....)</code></p></li>
  </ol>