SQL Script to Add Primary Key
Adding primary key using designer in SQL would take you so much time.
Here's a script that would automatically list all the tables without a primary key and create one. You can also filter by schema.
List all tables without Primary Key
Add Primary key
Here's a script that would automatically list all the tables without a primary key and create one. You can also filter by schema.
List all tables without Primary Key
select
a.table_name,
a.column_name,
a.ordinal_position
from information_schema.columns as a
inner join sys.tables as b on a.table_Name = b.name
where ordinal_position <= 1
and (object_id not in(SELECT object_id from sys.indexes WHERE is_primary_key=1))
Add Primary key
DECLARE cur CURSOR FOR
select
a.TABLE_SCHEMA as sn,
a.table_name as tn,
a.column_name as cn
from information_schema.columns as a
inner join sys.tables as b on a.table_Name = b.name
where table_schema in(schema names) and
ordinal_position <= 1 and
(object_id not in(SELECT object_id from sys.indexes WHERE is_primary_key=1)) and
substring(a.column_name, len(column_name)-1, 2) = 'Id'
DECLARE @sn sysname,
@tn sysname,
@cn sysname,
@sql varchar(500)
OPEN cur
FETCH NEXT FROM cur INTO @sn, @tn, @cn
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER TABLE [' + @sn + '].['+ @tn +'] ADD CONSTRAINT [PK_' +@tn +'_'+ @cn+ '] PRIMARY KEY CLUSTERED
(['+ @cn+'] ASC) ON [PRIMARY]'
PRINT @sql
exec (@sql)
FETCH NEXT FROM cur INTO @sn, @tn, @cn
END
CLOSE cur
DEALLOCATE cur
Happy coding ;)