title: How can I insert random values into a SQL Server table?
body: <p>I'm trying to randomly insert values from a list of pre-defined values into a table for testing. I tried using the solution found on this StackOverflow question:</p>
  
  <p><a href="https://stackoverflow.com/questions/1289600/update-sql-table-with-random-value-from-other-table"><code>stackoverflow.com/.../update-sql-table-with-random-value-from-other-table</code></a></p>
  
  <p>When I I tried this, all of my "random" values that are inserted are exactly the same for all 3000 records. </p>
  
  <p>When I run the part of the query that actually selects the random row, it does select a random record every time I run it by hand, so I know the query works. My best guesses as to what is happening are:</p>
  
  <ul>
  <li>SQL Server is optimizing the <code>SELECT</code> somehow, not allowing the subquery to be evaluated more than once</li>
  <li>The random value's seed is the same on every record the query updates</li>
  </ul>
  
  <p>I'm stuck on what my options are. Am I doing something wrong, or is there another way I should be doing this? </p>
  
  <p>This is the code I'm using:</p>
  
  <pre><code>DECLARE @randomStuff TABLE ([id] INT, [val] VARCHAR(100))
  
  INSERT INTO @randomStuff ([id], [val]) 
  VALUES ( 1,  'Test Value 1' )
  INSERT INTO @randomStuff ([id], [val])
  VALUES ( 2,  'Test Value 2' )
  INSERT INTO @randomStuff ([id], [val])
  VALUES ( 3,  'Test Value 3' )
  INSERT INTO @randomStuff ([id], [val])
  VALUES ( 4,  'Test Value 4' )
  INSERT INTO @randomStuff ([id], [val])
  VALUES ( 5,  'Test Value 5' )
  INSERT INTO @randomStuff ([id], [val])
  VALUES ( 6,  null )
  INSERT INTO @randomStuff ([id], [val])
  VALUES ( 7,  null )
  INSERT INTO @randomStuff ([id], [val])
  VALUES ( 8,  null )
  INSERT INTO @randomStuff ([id], [val])
  VALUES ( 9,  null )
  INSERT INTO @randomStuff ([id], [val])
  VALUES ( 10, null )
  
  UPDATE MyTable
  SET MyColumn = (SELECT TOP 1 [val] FROM @randomStuff ORDER BY NEWID())
  </code></pre>