SQL Server: Find Identity column, Seed and Increment Values of all tables in a database

One fine day I encountered an issue. Even though it was an issue, I mentioned fine day because I found solution and learned couple of things. The issue was - For a column there was an unexpected rise in auto generated number. So I needed to check whether a single table or all table are affected. I needed a query to find seed and increment values of a all tables in a database at a time. This query helped me.
SELECT IDENT_SEED(TABLE_SCHEMA + '.' + TABLE_NAME) AS Seed ,
IDENT_INCR(TABLE_SCHEMA + '.' + TABLE_NAME) AS Increment ,
IDENT_CURRENT(TABLE_SCHEMA + '.' + TABLE_NAME) AS CurrentIdentity ,
LOWER(TABLE_SCHEMA) + '.' + LOWER(TABLE_NAME) As TableName,
LOWER(COLUMN_NAME) As ColumnName,
UPPER(c.DATA_TYPE) AS DataType ,
t.MaxholdValue,
t.MaxholdValue -IDENT_CURRENT(TABLE_SCHEMA + '.' + TABLE_NAME) AS Remaining,
((t.MaxholdValue -IDENT_CURRENT(TABLE_SCHEMA + '.' + TABLE_NAME))/t.MaxholdValue) *100 AS PercentUnAllocated
FROM INFORMATION_SCHEMA.COLUMNS AS c
INNER JOIN ( SELECT name AS Data_Type ,
POWER(CAST(2 AS VARCHAR), ( max_length * 8 ) - 1) AS MaxholdValue
FROM sys.types
WHERE name LIKE '%Int'
) t ON c.DATA_TYPE = t.Data_Type
WHERE COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME), COLUMN_NAME,
'IsIdentity') = 1
ORDER BY PercentUnAllocated ASC

No comments:

Post a Comment