SQL递归索引查找查询

时间:2017-08-24 16:09:54

标签: sql sql-server indexing

我有查询列出我的数据库中的所有表及其各自的索引:

SELECT 
     TableName = t.name,
     IndexName = ind.name,
     IndexId = ind.index_id,
     ColumnId = ic.index_column_id,
     ColumnName = col.name,
     ind.*,
     ic.*,
     col.* 
FROM 
     sys.indexes ind 
INNER JOIN 
     sys.index_columns ic ON  ind.object_id = ic.object_id and ind.index_id = ic.index_id 
INNER JOIN 
     sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id 
INNER JOIN 
     sys.tables t ON ind.object_id = t.object_id 
WHERE 
     ind.is_primary_key = 0 
     AND ind.is_unique = 0 
     AND ind.is_unique_constraint = 0 
     AND t.is_ms_shipped = 0

我获得了这样的输出:

enter image description here

TableName -> contain Table names in DB ColumName -> contain Index column name for each table in DB

我的目标是绘制每个"TableName" + "ColumnName" TOT记录数和最后(最大)ColumnName值。

基本上,以标签格式输出我想获得: enter image description here

您是否知道如何在单个查询中递归生成此结果? 谢谢!

2 个答案:

答案 0 :(得分:1)

嗯,这可能足够快,可以在您的设置中运行,这是我最好的尝试。存在涉及列类型和max()聚合的问题,这表明max_value应该是varchar

在创建和执行此过程之前,请确保use your_database_name,这对于应用程序调用来说类似于单个查询。

create proc stp_generateColInfo as

declare
 @tablename varchar(1000),
 @columnname varchar(1000)

set nocount on

create table #TMP_DDL (
    TableName varchar(1000), 
    ColumnName varchar(1000),
    TOTAL int,
    MAX_VALUE varchar(8000)
);

INSERT INTO #TMP_DDL
SELECT 
     TableName = t.name,
     ColumnName = col.name,
     0 as TOTAL,
     '' as MAX_VALUE
FROM 
     sys.indexes ind 
INNER JOIN 
     sys.index_columns ic ON  ind.object_id = ic.object_id and ind.index_id = ic.index_id 
INNER JOIN 
     sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id 
INNER JOIN 
     sys.tables t ON ind.object_id = t.object_id 
WHERE 
     ind.is_primary_key = 0 
     AND ind.is_unique = 0 
     AND ind.is_unique_constraint = 0 
     AND t.is_ms_shipped = 0


declare cs cursor local static forward_only for
    select TableName, ColumnName from #TMP_DDL

open cs
fetch next from cs into @tablename, @columnname
while @@FETCH_STATUS=0
begin
    exec('
    declare @total int, @max_value varchar(8000)
    select @total=count(*), @max_value=max(IsNull(' + @columnname + ',0)) from ' + @tablename + '
    update #TMP_DDL set total=@total, max_value=@max_value where TableName=''' + @tablename + ''' and ColumnName=''' + @columnname + ''''
    )
    fetch next from cs into @tablename, @columnname
end

close cs
deallocate cs

set nocount off

--Add joins here to select additional columns :)
select * from #TMP_DDL

go

答案 1 :(得分:1)

  

你知道如何在a中递归生成这个结果吗?   单一查询?

这是不可能的。

您需要调用动态sql语句

SET @sql = 'SELECT @MaxID = MAX('+@ColumnName+') FROM '+@TableName

分别为结果集的每一行和functions cannot contain dynamic SQL分别在SQL Server中将其写为一个select语句。您不能在一个查询中分别为每一行调用动态SQL或a stored procedure

在Oracle中,有BULK COLLECT and FORALL之类的命令允许将结果集与逐行处理相结合,但我不知道SQL Server中存在类似的内容。