将主键添加到数据库中的某些现有表

时间:2015-06-11 01:17:56

标签: sql sql-server database for-loop primary-key

我有一个包含600多个表的数据库。有些表有主键,有些表没有。我怎样才能动态:

1.循环遍历所有表格 2.选择没有主键的那些 3.添加自动增量字段
4.将此字段设为主键

我认为它将是以下的组合:

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

1 个答案:

答案 0 :(得分:3)

此查询将排除所有具有主键或标识列的表,然后在剩余对象上添加标识列和主键

DECLARE @PKScript AS VARCHAR(max) = '';
SELECT @PKScript += 
    '  ALTER TABLE ' + QUOTENAME(SCHEMA_NAME(obj.SCHEMA_ID))+'.'+ QUOTENAME(obj.name) + 
                      ' ADD PK_ID BIGINT IDENTITY;' +
     ' ALTER TABLE ' + QUOTENAME(SCHEMA_NAME(obj.SCHEMA_ID))+'.'+QUOTENAME(obj.name) + 
                     ' ADD CONSTRAINT PK_ID_' + obj.name+ ' PRIMARY KEY NONCLUSTERED (PK_ID) '
 FROM sys.objects obj
 WHERE object_id not in
     (select parent_object_id
      from sys.key_constraints 
      where type = 'PK'
      UNION
      Select object_id
      from sys.identity_columns
      )
      AND type = 'U'
--PRINT (@PKScript);
EXEC(@PKScript);  

对于已定义标识列的表,您可以使用此查询将此标识列设置为主键(因为在同一个表上不能有两个标识列)

DECLARE @PKScript2 VARCHAR(max)='';

SELECT @PKScript2 += ' ALTER TABLE ' + QUOTENAME(SCHEMA_NAME(obj.SCHEMA_ID))+'.'+
       QUOTENAME(obj.name) + ' ADD CONSTRAINT PK_' + icol.name +'_'+ obj.name+
       ' PRIMARY KEY NONCLUSTERED (' + QUOTENAME(icol.name) + ')' + CHAR(13)
FROM sys.identity_columns icol INNER JOIN 
     sys.objects obj on icol.object_id= obj.object_id
WHERE NOT EXISTS (SELECT * FROM sys.key_constraints k
                  WHERE k.parent_object_id = obj.object_id
                        AND k.type = 'PK')
      AND obj.type = 'U'
--PRINT (@PKScript2);
EXEC(@PKScript2);