title: Adding primary key to some exising tables in a database
body: <p>I have a database with over 600 tables. Some of the tables have primary keys and some do not. How can I dynamically:<br/><br/>
  1. loop through all tables<br/>
  2. select ones that do not have primary keys<br/>
  3. add an auto incremented field<br/>
  4. make this field the primary key<br/><br/></p>
  
  <p>I would presume it would be a combination of the following:</p>
  
  <pre><code>USE MyDataBase; 
  GO
  -- List all tables without primary constraint
  SELECT i.name AS IndexName, 
      OBJECT_NAME(ic.OBJECT_ID) AS TableName, 
      COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
  FROM sys.indexes AS i
  INNER JOIN sys.index_columns AS ic
  ON i.OBJECT_ID = ic.OBJECT_ID
  AND i.index_id = ic.index_id
  WHERE i.is_primary_key = 0
  GO
  
  -- add new auto incremented field
  ALTER TABLE MyTable 
  ADD PK_ID BIGINT IDENTITY;
  GO
  
  -- create new primary key constraint
  ALTER TABLE MyTable 
  ADD CONSTRAINT PK_ID PRIMARY KEY NONCLUSTERED (PK_ID);
  GO
  </code></pre>