SQL Script to Add Identity Column

Supposing you have 50 tables without identity column, adding identity manually in the table designer would take you so much time. Here's a script to automatically add identity to a column.

List all tables without identity column.
SELECT 
(SCHEMA_NAME(schema_id) + '.' + name) as SchemaTable
FROM sys.tables
WHERE [name] NOT IN
(
SELECT 
OBJECT_NAME(OBJECT_ID) AS TABLENAME
FROM SYS.IDENTITY_COLUMNS
)
ORDER BY SchemaTable;
GO

Add identity
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 
table_name NOT IN(SELECT OBJECT_NAME(OBJECT_ID) AS TABLENAME   FROM SYS.IDENTITY_COLUMNS)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 ' + @tn +' int NOT NULL IDENTITY (1,1)'    
PRINT @sql   
exec (@sql)  
FETCH NEXT FROM cur INTO @sn, @tn, @cn     
END 
CLOSE cur     
DEALLOCATE cur

Happy coding :)
 

No comments:

Post a Comment