SQL:打印表索引脚本
SQL SERVER 打印索引脚本
declare C1 cursor for -- 表索引,不包含主约束索引。 SELECT OBJ.OBJECT_ID AS [TABLE_ID], OBJ.NAME AS [TABLE_NAME], -- PK.name AS CONSTRAIN_NAME, idx.name as index_name, --索引类型: 聚集索引、非聚集索引 case WHEN idx.type = 1 then 'CLUSTERED' when idx.type=2 then 'NONCLUSTERED' ELSE '' END AS [INDEX_TYPE], CASE WHEN IDX.is_unique=1 THEN 'UNIQUE' WHEN IDX.is_unique=0 THEN '不唯一' ELSE '' END [IS_UNIQUE_DESC] -- IDXC.index_column_id, -- IDXC.key_ordinal, -- COL.name AS COLUMN_NAME -- ,IDX.* FROM SYS.all_objects OBJ, -- SYS.key_constraints PK, sys.indexes idx -- sys.index_columns idxc, -- SYS.all_columns COL WHERE OBJ.type='U' AND OBJ.name LIKE 'AP_Vouch%' -- AND OBJ.object_id = PK.parent_object_id -- AND PK.type='PK' -- and pk.parent_object_id = idx.object_id -- and pk.unique_index_id = idx.index_id and not exists ( select 1 from SYS.key_constraints PK where pk.parent_object_id = idx.object_id and pk.unique_index_id = idx.index_id ) and obj.object_id = idx.object_id -- AND IDX.object_id = IDXC.object_id -- and idx.index_id = idxc.index_id -- AND IDXC.object_id = COL.object_id --and IDXC.column_id = COL.column_id order by OBJ.NAME, idx.name --,IDXC.key_ordinal ; DECLARE @TABLE_ID BIGINT, @TABLE_NAME NVARCHAR(128), @INDEX_NAME NVARCHAR(128), @INDEX_TYPE NVARCHAR(128), @IS_UNIQUE_DESC NVARCHAR(128), @KEY_ORDINAL INT, @COLUMN_NAME NVARCHAR(128), @RESULT NVARCHAR(4000), @COLUMN_LIST NVARCHAR(4000), @UNIQUE NVARCHAR(20); declare @fetch_status1 int; declare @fetch_status_idx int; BEGIN OPEN C1 ; FETCH NEXT FROM C1 INTO @TABLE_ID, @TABLE_NAME, @INDEX_NAME, @INDEX_TYPE,@IS_UNIQUE_DESC--, @KEY_ORDINAL ,@COLUMN_NAME; set @fetch_status1 =@@FETCH_STATUS WHILE @FETCH_STATUS1 = 0 BEGIN IF @IS_UNIQUE_DESC = 'UNIQUE' SET @UNIQUE = ' UNIQUE '; ELSE SET @UNIQUE =' '; SET @COLUMN_LIST =''; -- 索引字段 declare c_idxc cursor for select IDXC.key_ordinal, COL.name AS COLUMN_NAME from sys.indexes idx, sys.index_columns idxc, SYS.all_columns COL where IDXC.object_id = COL.object_id and IDXC.column_id = COL.column_id AND IDX.index_id = IDXC.index_id and idxc.object_id = @table_id AND IDX.name = @INDEX_NAME ORDER BY IDXC.key_ordinal; open c_idxc ; fetch next from c_idxc into @key_ordinal, @column_name set @fetch_status_idx = @@FETCH_STATUS while @fetch_status_idx = 0 begin set @COLUMN_LIST = @COLUMN_LIST + @COLUMN_NAME + ','; fetch next from c_idxc into @key_ordinal, @column_name set @fetch_status_idx = @@FETCH_STATUS end; close c_idxc; deallocate c_idxc; IF @COLUMN_LIST!='' SET @COLUMN_LIST = LEFT(@COLUMN_LIST,LEN(@COLUMN_LIST)-1); SET @RESULT='CREATE '+ @UNIQUE + @INDEX_TYPE +' INDEX '+ @INDEX_NAME +' ON '+ @TABLE_NAME + '( '+ @COLUMN_LIST + ' );'+CHAR(13); PRINT @RESULT; -- PRINT 'GO'; FETCH NEXT FROM C1 INTO @TABLE_ID, @TABLE_NAME, @INDEX_NAME, @INDEX_TYPE,@IS_UNIQUE_DESC--, @KEY_ORDINAL ,@COLUMN_NAME ; set @fetch_status1 = @@FETCH_STATUS; END ; CLOSE C1; DEALLOCATE C1; END ;
优质生活从拆开始