I am working on script in which I need to get all table record count and index created on that table for all database on server. I am able to achieve this functionality but I had to mentioned database name statically.
Here is script I am using
declare @TableList TABLE(Id int IDENTITY(1,1),DataBaseName VARCHAR(100),TableName VARCHAR(100),RecordCount INT,NameOfIndex VARCHAR(100),TypeOfIndex VARCHAR(100))
declare @TableListWithIndex TABLE(Id int IDENTITY(1,1),DataBaseName VARCHAR(100),TableName VARCHAR(100),NameOfIndex VARCHAR(100),TypeOfIndex VARCHAR(100))
INSERT INTO @TableList(DataBaseName,TableName,RecordCount)
SELECT 'DBNAME1',T.name AS [TABLE NAME],
I.rows AS [ROWCOUNT]
FROM DBNAME1.sys.tables AS T
INNER JOIN DBNAME1.sys.sysindexes AS I
ON T.object_id = I.id
AND I.indid < 2
ORDER BY I.rows DESC
INSERT INTO @TableListWithIndex(DataBaseName,TableName,NameOfIndex,TypeOfIndex)
SELECT
'DBNAME1',
TableName = t.name,
IndexName = ind.name,
ind.type_desc
FROM
DBNAME1.sys.indexes ind
INNER JOIN
DBNAME1.sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id
INNER JOIN
DBNAME1.sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id
INNER JOIN
DBNAME1.sys.tables t ON ind.object_id = t.object_id
WHERE
ind.is_primary_key = 0
AND ind.is_unique = 0
AND ind.is_unique_constraint = 0
AND t.is_ms_shipped = 0
ORDER BY
t.name, ind.name, ind.index_id, ic.index_column_id
END --FOR DBNAME1
update TL
SET TL.NameOfIndex = TLW.NameOfIndex,TL.TypeOfIndex = TLW.TypeOfIndex
from @TableList TL
INNER JOIN @TableListWithIndex TLW ON TL.TableName = TLW.TableName
AND TL.DataBaseName = TLW.DataBaseName
select * from @TableList order by Id
SO for Database2 I had to write whole code above update statement.. in order to get all records and Index name from 2 database.
But how I can achieve this functionality dynamically, where I don't need to hardcode database name.
Thanks In advance