我知道我可以使用以下命令索引表中的列:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
但是,我有一个250个模式的数据库,每个模式有10个表。我如何,对于每个表,检查列是否存在,然后为其创建索引(如果它存在)?
我正在使用SQL Server 2012。
答案 0 :(得分:5)
香蕉答案的一个小变化是使用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
答案 1 :(得分:2)
实现目标的简单方法是loop over all tables through information_schema.tables
,然后创建索引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