Create indexes for all tables in a database?
I know I can index a column in a table using the command:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
However, I have a database of 250 schemas with 10 tables each. How can I, for each table , check if a column exists and then create an index on it (if it exists)?
I am using SQL Server 2012.
+3
source to share
2 answers
A small variation on Banana's answer is to use INFORMATION_SCHEMA.COLUMNS to get the final list of tables directly:
-- Define column to index.
DECLARE @coltoindex VARCHAR(20), @indexoptions VARCHAR(30)
SET @coltoindex = 'Id'
SET @indexoptions = 'UNIQUE'
--USE database_name
--IF OBJECT_ID('tempdb..#tables') IS NOT NULL DROP TABLE #tables
SELECT table_schema, table_name INTO #tables FROM information_schema.columns
where COLUMN_NAME = @coltoindex
DECLARE @schema VARCHAR(30), @table VARCHAR(20), @sqlCommand varchar(1000)
WHILE (SELECT COUNT(*) FROM #tables) > 0
BEGIN
SELECT TOP 1 @schema = table_schema, @table = table_name FROM #tables
SET @sqlCommand = '
CREATE ' + @indexoptions + ' INDEX
idx_' + @schema + '_' + @table + '_' + @coltoindex + '
ON ' + @schema + '.' + @table + ' (' + @coltoindex + ')'
-- print @sqlCommand
EXEC (@sqlCommand)
DELETE FROM #tables WHERE table_schema = @schema AND table_name = @table
END
+5
source to share
An easy way to achieve what you want is to loop through all tables throughinformation_schema.tables
, and then create an index if the row exists in that table :
-- Define column to index.
DECLARE @coltoindex VARCHAR(20), @indexoptions VARCHAR(30)
SET @coltoindex = 'Id'
SET @indexoptions = 'UNIQUE'
USE database_name
--IF OBJECT_ID('tempdb..#tables') IS NOT NULL DROP TABLE #tables
SELECT table_schema, table_name INTO #tables FROM information_schema.tables
DECLARE @schema VARCHAR(30), @table VARCHAR(20), @sqlCommand varchar(1000)
WHILE (SELECT COUNT(*) FROM #tables) > 0
BEGIN
SELECT TOP 1 @schema = table_schema, @table = table_name FROM #tables
SET @sqlCommand = '
IF EXISTS(SELECT * FROM sys.columns
WHERE [name] = N''' + @coltoindex + '''
AND [object_id] = OBJECT_ID(N''' + @schema + '.' + @table + '''))
BEGIN
CREATE ' + @indexoptions + ' INDEX
idx_' + @schema + '_' + @table + '_' + @coltoindex + '
ON ' + @schema + '.' + @table + ' (' + @coltoindex + ')
END'
EXEC (@sqlCommand)
DELETE FROM #tables WHERE table_schema = @schema AND table_name = @table
END
+2
source to share