Create indexes for all tables in database?

I know I can index a column in a table with 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 for it (if it does exist)?

I am using SQL Server 2012.


Banana答案的一个小变化是使用INFORMATION_SCHEMA.COLUMNS直接获取最终的表格列表:

-- 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

实现您想要的一种简单方法是通过information_schema.tables遍历所有表,然后在该表存在行的情况下创建索引:

-- 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
链接地址: http://www.djcxy.com/p/94420.html

上一篇: 检查SQL Server数据库表中是否存在表或列

下一篇: 为数据库中的所有表创建索引?