SQL SERVER2008 自動生成索引

2021-07-05 23:36:34 字數 2523 閱讀 6342

declare @ix table(index_handle int,eq nvarchar(4000),included_columns nvarchar(4000),name varchar(100),dbname varchar(30))

;with idx as(

select a.index_handle ,a.equality_columns,a.inequality_columns,a.equality_columns+case when a.inequality_columns is null then '' else ','+a.inequality_columns end as eq ,a.included_columns,b.name,c.name dbname

from sys.[dm_db_missing_index_details] a 

inner join sysobjects b on a.object_id=b.id

inner join master..sysdatabases c on c.dbid=a.database_id

where a.equality_columns>''

union all

select a.index_handle ,a.equality_columns,a.inequality_columns,case when a.inequality_columns is null then '' else a.inequality_columns end as eq ,a.included_columns,b.name,c.name dbname

from sys.[dm_db_missing_index_details] a 

inner join sysobjects  b on a.object_id=b.id  --預設當前的資料庫

inner join master..sysdatabases c on c.dbid=a.database_id

where a.equality_columns is null

),ind1 as( 

select index_handle,eq,included_columns,name,dbname

,(select count(1) from sys.[dm_db_missing_index_columns](index_handle) where column_usage<>'include' )leng

,(select count(1) from sys.[dm_db_missing_index_columns](index_handle) where column_usage='include' )leng1

from idx

),ind2 as( select row_number() over(partition by name order by leng desc,leng1 desc ) as rownum,* from ind1)

insert into @ix(index_handle,eq,included_columns,name,dbname)

select index_handle,eq,included_columns,name,dbname from ind2 where rownum=1

declare @sql table(strsql nvarchar(3000))

insert into @sql( strsql )

select 

' use ['+dbname+']'+char(13)+char(10)

+' create nonclustered index ix_'+name+'_'+cast(index_handle as varchar(10))+char(13)+char(10)

+' on [dbo].['+name+'] ('+eq+')'+char(13)+char(10)

+ case when included_columns is null then '' else ' include('+included_columns+')'+char(13)+char(10) end

from @ix

declare @cursql nvarchar(3000)=''

declare idx_cursor cursor --定義游標

for (select strsql from @sql) --查出需要的集合放到游標中

open idx_cursor; --開啟游標

fetch next from idx_cursor into @cursql ; --讀取第一行資料

while @@fetch_status = 0

begin

print(@cursql) --輸出

--exec(@cursql);--執行

fetch next from idx_cursor into @cursql; --讀取下一行資料

endclose idx_cursor; --關閉游標

deallocate idx_cursor; --釋放游標

select strsql as content from @sql

go

sql server 2008 自動備份

身份驗證 包含windows身份驗證和 sql server身份驗證,此處選擇windows 身份驗證 選擇 管理 維護計畫 維護計畫嚮導 必須啟用 服務 啟動模式請改為自動 備份資料到特定目錄時出現拒絕訪問,然後測試備份到c盤根目錄正常。但是就是需要備份到特定的專案目錄中。查了下原因 是因為那個目...

SQL Server 2008 資料庫自動備份

首先需要啟動sql server agent sql server 服務,這個服務如果不啟動是無法執行新建作業的。1 點選 開始 所有程式 microsoft sql server 2008 啟動sql server management studio 登入資料庫,點選管理 維護計畫 右擊 維護計畫...

Sql Server 2008 收縮日誌

收縮日誌 alter database dnname set recovery with no wait goalter database dnname set recovery 簡單模式 gouse dnname godbcc shrinkfile n dnname log 11,truncate...