0

为了更好地理解数据库中的所有关系(物理和逻辑),我正在寻找存储过程以提取连接谓词。我有一些我可以使用的东西,但它并不完整。

目标是在结果中有 3 列:

  1. 对象名称
  2. 第一个连接谓词
  3. 第二个连接谓词
  4. 连接类型(内、右、左)

    declare @Schema varchar(50),@SearchString   VARCHAR (10)
    
    set @SearchString = 'join';
    
    set  @Schema = 'dbo'
    
    
    declare @TextBuffer table 
    (
    SchemaName varchar(50) NOT NULL,
    ObjectName varchar(100) NOT NULL,
    Occurance int NOT NULL, 
    Txt varchar(4000) NOT NULL,
    Colid int
    )
    
    declare @Occurance table
    (
    SchemaName varchar(50)   NULL,
    ObjectName varchar(100)   NULL,
    Occurance  varchar(500) 
    )
    
    
    
    INSERT INTO @TextBuffer
    
    SELECT   DISTINCT SCHEMA_NAME(o.schema_id),
                      o.name,
                      (LEN(text) - LEN(REPLACE(text, @SearchString, ''))) / LEN(@SearchString),
                      [text],
                      colid
    FROM     syscomments AS c
             INNER JOIN
             sys.objects AS o
             ON c.id = o.[object_id]
             INNER JOIN
             sys.schemas AS s
             ON o.schema_id = s.schema_id
    WHERE    text LIKE '%' + @SearchString + '%'
             AND SCHEMA_NAME(o.schema_id) = @Schema
    ORDER BY colid, 3 DESC;
    
    
    
    DECLARE @Txt varchar(4000), @ObjectName varchar(100), @Occ int, @SchemaName varchar(100)
    
    
    declare @count int, @position int
    set @count = 0
    set @position = 0
    
    DECLARE my_cursor CURSOR FAST_FORWARD FOR 
    
    SELECT Txt,ObjectName, Occurance, SchemaName from @TextBuffer
    OPEN my_cursor
    
    FETCH NEXT FROM my_cursor INTO @Txt,@ObjectName,@Occ,@SchemaName
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
    
        set @count =  @Occ
    
    
        while(@count > 0)
            begin 
    
            set @position =  charindex(@SearchString,@Txt) 
    
            insert into @Occurance select @SchemaName, @ObjectName, cast(substring(@Txt, @position, len(@Txt)) as varchar(500))
    
            set @Txt =  substring(substring(@Txt,len(@SearchString),len(@Txt)), @position, len(@Txt))
    
    
            set @count = @count -1
    
            end
    
    
    
    FETCH NEXT FROM my_cursor INTO @Txt,@ObjectName,@Occ,@SchemaName
    END
    
    CLOSE my_cursor 
    DEALLOCATE my_cursor 
    
    
    select * from @Occurance
    
4

0 回答 0