2012-10-01 8 views
5

SQL Serverデータベース内の既存のすべてのインデックスに対してCREATE INDEXステートメントをリストするスクリプトを持っている人はいますか?SQL ServerでCREATE INDEXステートメントを生成

このスレッドList of all index & index columns in SQL Server DBには、それらの検索方法に関するヒントがあります。しかし、CREATE INDEXステートメントを生成するスクリプトは素晴らしいでしょう。適切なデータがない状況に陥ったり、ドキュメントがなくても索引が時間の経過とともに非定型で追加されたりすることがあります。そのため、create文はありません。状況のように、私は今自分自身を見つける。

ありがとうございました。

+1

[データベース内のすべてのインデックスのスクリプトを生成]の可能な複製(http://stackoverflow.com/questions/9089700/generate-script-of-all-the-indexes-in-a-database) – bummi

答えて

10

使用私はしばらく前にそのために何かを書いたSQL管理Studioからスクリプトを生成し、「スクリプトの索引」オプション(高度なスクリプトオプションの下に)

+0

これは完璧に働いた。ありがとうございました! (そして他の人にも感謝しています)。 – royappa

+3

私は明白なことを述べているかもしれませんが、データベースに右クリック - >タスク - >スクリプトを生成... –

3

を選択してください。必要に応じて修正する必要がありますが、少なくともスケルトンがあります。あなたがインデックスに「オブジェクトエクスプローラ」ウィンドウ

Go]を使用して、テーブル単位でテーブルの上にそれを行うことができます

if exists (select 1 from information_schema.routines where routine_name = 'Script_CreateIndex') 
    drop proc Script_CreateIndex 
go 

create proc Script_CreateIndex (
    @TableName varchar(124) 
) 
as 
begin 
    if not exists (select 1 from sys.indexes where object_name(object_id) = @TableName and type_desc in ('CLUSTERED', 'NONCLUSTERED')) 
     return 

    declare @IndexList table (
     Id int identity, 
     IndexName varchar(124), 
     IndexDescription varchar(max), 
     IndexKeys varchar(max) 
    ) 

    insert @IndexList(IndexName, IndexDescription, IndexKeys) 
     exec sp_helpindex @TableName 

    if (select count(*) from @IndexList) > 0 
    begin 
     select '-- Creating indexes for table ' + @TableName 

     while exists (select 1 from @IndexList) 
     begin 
      declare @Id int, @IndexName varchar(124), @IndexDescription varchar(max), @IndexKeys varchar(max) 
      select top 1 @Id = Id, @IndexName = IndexName, @IndexDescription = IndexDescription, @IndexKeys = IndexKeys from @IndexList order by Id 
      delete from @IndexList where Id = @Id 

      declare @Clustered varchar(10), @Unique varchar(7) 

      select @Clustered = case when patindex('%nonclustered%', @IndexDescription) > 0 then '' else ' clustered ' end 
      select @Unique = case when patindex('%unique%', @IndexDescription) > 0 then ' unique ' else '' end 

      select 'if not exists (select 1 from sys.indexes where name = ''' + @IndexName + ''')' 
      select 'begin' 
      select char(9) + 'create' + @Unique + @Clustered + ' index [' + @IndexName + '] on [' + @TableName + '](' + @IndexKeys + ')' 
      select char(9) + 'select ''Index ' + @IndexName + ' created.''' 
      select 'end' 
      select 'go' 
     end 

     select '' 
     select '' 
    end 
end 
go 

grant exec on Script_CreateIndex to public 
select 'Script_CreateIndex compiled.' 'Job' 
go 
1

は管理スタジオでフォルダ、フォルダを強調表示し、[オブジェクトエクスプローラ]ペイン

を開きます

その後、そのテーブルのすべてのインデックスを「シフト選択」することができます。右クリックして「CREATE TO」を実行すると、関連するすべてのインデックスを含むスクリプトが作成されます。

関連する問題