SQL: SQL Server 打印索引源代码

SQL: SQL Server 打印索引源代码,在SQL SERVER 2008R2 开发版测试通过 。

-- 索引查詢  
declare  idx_cur cursor scroll for  
 select top 900
    tb.object_id as table_id,
    tb.name as table_name ,
    idx.name as index_name,
    col.column_id,
    col.name as column_name,
    --ix.object_id as index_id,
    ix.is_unique,
    ix.type_desc, 
    idxcol.index_column_id ,
    COUNT(idxcol.key_ordinal) OVER(PARTITION BY TB.NAME,idx.name )  AS CNT
  --  , idx.* 
  from sys.tables tb
  inner join  sys.sysindexes idx  on idx.id = tb.object_id and tb.type= 'U' 
  inner join sys.indexes ix  on  ix.name = idx.name   and ix.object_id = idx.id 
  inner JOIN SYS.index_columns  IDXCOL ON IDX.id = IDXCOL.object_id and idx.indid = idxcol.index_id 
  left join sys.all_columns col on col.object_id = idxcol.object_id and col.column_id = idxcol.column_id
  where 1=1 
    and  tb.name like '%%'
    and not exists ( select 1 from  SYS.key_constraints PK
   where  pk.parent_object_id = ix.object_id
    and pk.unique_index_id = ix.index_id )  --排除主鍵索引
 order by tb.name ,   idx.name,
  idxcol.index_id , idxcol.index_column_id;    
  declare @table_id bigint,
  @table_name nvarchar(250),
  @index_name nvarchar(250),  
  @column_id bigint,
  @column_name nvarchar(250),
  @is_unique bit,
  @type_desc nvarchar(250),
  @index_column_id bigint ;
 declare @sql nvarchar(4000), @index_list nvarchar(4000) , @sql_end nvarchar(50) ; 
 declare @is_unique_str nvarchar(20) = 'UNIQUE'; 
 DECLARE @CNT INT , @rows int =0 ;
begin
  set @rows = 0 ;
  set @index_list = ' ';
   set @sql_end = ' ) ON [PRIMARY] '+ NCHAR(13) + 'GO' + NCHAR(13) ;
  open idx_cur ;
  fetch first from idx_cur into @table_id ,
  @table_name ,
  @index_name ,  
  @column_id ,
  @column_name ,
  @is_unique,
  @type_desc ,
  @index_column_id ,
  @cnt ;
  while @@FETCH_STATUS = 0 
  begin
    set @rows = @rows +1 ;
  
   if @rows = 1 
   begin   
   set @index_list = '';
   if @is_unique = 1 
     set @is_unique_str = 'UNIQUE';  
   else 
     set @is_unique_str = ' '; 
      
    set @sql = 'CREATE ' + @is_unique_str + ' ' + @type_desc + ' INDEX [' + @index_name 
      + '] ON ['+ @TABLE_NAME +'] ( ' ;
   end ;
   
   set @index_list = @index_list + '['+@column_name+'],'  ;
      
   if @ROWS  = @CNT 
   begin
     --print 'end line' + str(@ROWS ) ; 
     set @rows = 0 ;
     SET @index_list = LEFT(@index_list, len(@index_list)-1)
     set @sql = @sql + @index_list + @sql_end ;
     print  @sql ; 
   end ;
  /* else
   begin
    --  print 'Not end line' + str(@ROWS );  
     PRINT ''
   end;   
   */  
    fetch next from idx_cur into @table_id ,
  @table_name ,
  @index_name ,  
  @column_id ,
  @column_name ,
  @is_unique,
  @type_desc ,
  @index_column_id,
  @cnt  ;
  end;
  close idx_cur;
  deallocate idx_cur ;
     
end;

  

image

 

posted @ 2026-11-10 09:00  samrv  阅读(8)  评论(0)    收藏  举报