AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 99043
Accepted
HelloWorld1
HelloWorld1
Asked: 2015-04-29 04:38:27 +0800 CST2015-04-29 04:38:27 +0800 CST 2015-04-29 04:38:27 +0800 CST

Localize uma palavra específica em um banco de dados

  • 772

Meta

Localize uma palavra específica entre as tabelas de um banco de dados e exiba o nome da tabela e da coluna em uma lista.

Problema

Existem tabelas DEMASIADAS para localizar uma palavra específica no banco de dados.

Informações

  • Usando o SQLServer 2012
  • Cada tabela usa um 'schemaname.tablename'
sql-server sql-server-2012
  • 2 2 respostas
  • 2417 Views

2 respostas

  • Voted
  1. Best Answer
    Aaron Bertrand
    2015-04-29T04:57:36+08:002015-04-29T04:57:36+08:00

    Isso não será rápido (levou mais de um minuto para produzir 0 resultados em minha cópia local do AdventureWorks).

    DECLARE @SpecificWord NVARCHAR(32);
    SET @SpecificWord = N'donut';
    
    
    DECLARE @sql NVARCHAR(MAX);
    SET @sql = N'SELECT NULL,NULL WHERE 1 = 0';
    SET @SpecificWord = N'%' + @SpecificWord + N'%';
    
    SELECT @sql += N' UNION ALL SELECT '''
     + QUOTENAME(s.name) + N'.' + QUOTENAME(t.name)
     + ''',''' + QUOTENAME(c.name) + ''' WHERE EXISTS
     (
       SELECT 1 FROM ' + QUOTENAME(s.name) + N'.' + QUOTENAME(t.name)
         + N' WHERE ' + QUOTENAME(c.name) + N' LIKE @s
     )'
    FROM sys.columns AS c
    INNER JOIN sys.tables AS t
    ON c.[object_id] = t.[object_id]
    INNER JOIN sys.schemas AS s
    ON t.[schema_id] = s.[schema_id]
    WHERE c.system_type_id IN (35,99,167,175,231,239);
    
    EXEC sys.sp_executesql @sql, N'@s NVARCHAR(32)', @SpecificWord;
    

    Se você precisar apoiar sql_variantpor algum motivo (recomendo contra isso), apenas algumas alterações são necessárias:

    DECLARE @SpecificWord NVARCHAR(32);
    SET @SpecificWord = N'donut';
    
    
    DECLARE @sql NVARCHAR(MAX);
    SET @sql = N'SELECT NULL,NULL WHERE 1 = 0';
    SET @SpecificWord = N'%' + @SpecificWord + N'%';
    
    SELECT @sql += N' UNION ALL SELECT '''
     + QUOTENAME(s.name) + N'.' + QUOTENAME(t.name)
     + ''',''' + QUOTENAME(c.name) + ''' WHERE EXISTS
     (SELECT 1 FROM ' + QUOTENAME(s.name) + N'.' 
     + QUOTENAME(t.name) + N' WHERE CONVERT(
       NVARCHAR(MAX), ' + QUOTENAME(c.name) 
     + N') LIKE @s)'
    FROM sys.columns AS c
    INNER JOIN sys.tables AS t
    ON c.[object_id] = t.[object_id]
    INNER JOIN sys.schemas AS s
    ON t.[schema_id] = s.[schema_id]
    WHERE c.system_type_id IN (35,98,99,167,175,231,239);
    
    EXEC sys.sp_executesql @sql, N'@s NVARCHAR(32)', @SpecificWord;
    
    • 9
  2. 3 revsuser126897
    2017-08-05T05:32:53+08:002017-08-05T05:32:53+08:00

    Resposta do wiki da comunidade :

    Você pode usar o script a seguir, que foi usado para localizar dados incorretos. Pode não ser rápido, mas funcionou para mim em várias ocasiões quando precisei:

    /*
    - Search through tables to find specific text
    - Written by Luis Chiriff (with help from SQL Server Central)
    - [email protected] @ 24/11/2008 @ 11:54
    */
    
    -- Variable Declaration
    
    Declare @StringToFind VARCHAR(200), @Schema sysname, @Table sysname, @FullTable int, @NewMinID int, @NewMaxID int,
    @SQLCommand VARCHAR(8000), @BaseSQLCommand varchar(8000), @Where VARCHAR(8000), @CountCheck varchar(8000) , @FieldTypes varchar(8000),
    @cursor VARCHAR(8000), @columnName sysname, @SCn int, @SCm int
    Declare @TableList table (Id int identity(1,1) not null, tablename varchar(250))
    Declare @SQLCmds table (id int identity(1,1) not null, sqlcmd varchar(8000))
    Declare @DataFoundInTables table (id int identity(1,1) not null, sqlcmd varchar(8000))
    
    
    -- Settings
    
    SET @StringToFind = 'territory'
    SET NOCOUNT ON
    SET @StringToFind = '%'+@StringToFind+'%'
    
    -- Gathering Info
    
    if ((select count(*) from sysobjects where name = 'tempcount') > 0)
        drop table tempcount
    
    create table tempcount (rowsfound int)
    insert into tempcount select 0
    
        -- This section here is to accomodate the user defined datatypes, if they have
        -- a SQL Collation then they are assumed to have text in them.
        SET @FieldTypes = ''
        select @FieldTypes = @FieldTypes + '''' + rtrim(ltrim(name))+''',' from systypes where collation is not null or xtype = 36
        select @FieldTypes = left(@FieldTypes,(len(@FieldTypes)-1))
    
    insert into @TableList (tablename) 
        select name from sysobjects 
        where xtype = 'U' and name not like 'dtproperties' 
        order by name
    
    -- Start Processing Table List
    
    select @NewMinID = min(id), @NewMaxID = max(id) from @TableList
    
    while(@NewMinID <= @NewMaxID)
        Begin
    
        SELECT @Table = tablename, @Schema='dbo', @Where = '' from @TableList where id = @NewMinID
    
        SET @SQLCommand = 'SELECT * FROM ' + @Table + ' WHERE' 
        -- removed ' + @Schema + '.
    
        SET @cursor = 'DECLARE col_cursor CURSOR FOR SELECT COLUMN_NAME
        FROM [' + DB_NAME() + '].INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = ''' + @Schema + '''
        AND TABLE_NAME = ''' + @Table + '''
        AND DATA_TYPE IN ('+@FieldTypes+')'
        --Original Check, however the above implements user defined data types --AND DATA_TYPE IN (''char'',''nchar'',''ntext'',''nvarchar'',''text'',''varchar'')'
    
        EXEC (@cursor)
    
        SET @FullTable = 0
        DELETE FROM @SQLCmds
    
        OPEN col_cursor   
        FETCH NEXT FROM col_cursor INTO @columnName   
    
        WHILE @@FETCH_STATUS = 0   
        BEGIN   
    
            SET @Where = @Where + ' [' + @columnName + '] LIKE ''' + @StringToFind + ''''
            SET @Where = @Where + ' OR'
    
            --PRINT @Table + '|'+ cast(len(isnull(@Where,''))+len(isnull(@SQLCommand,'')) as varchar(10))+'|'+@Where
    
            if (len(isnull(@Where,''))+len(isnull(@SQLCommand,'')) > 3600)
                Begin
                    SELECT @Where = substring(@Where,1,len(@Where)-3)
                    insert into @SQLCmds (sqlcmd) select @Where
                    SET @Where = ''
                End
    
            FETCH NEXT FROM col_cursor INTO @columnName   
        END   
    
        CLOSE col_cursor   
        DEALLOCATE col_cursor 
    
        if (@Where <> '')
            Begin
                SELECT @Where = substring(@Where,1,len(@Where)-3)
                insert into @SQLCmds (sqlcmd) 
                    select @Where --select @Table,count(*) from @SQLCmds
            End
    
        SET @BaseSQLCommand = @SQLCommand
    
        select @SCn = min(id), @SCm = max(id) from @SQLCmds
        while(@SCn <= @SCm)
            Begin
    
            select @Where = sqlcmd from @SQLCmds where ID = @SCn
    
            if (@Where <> '')
                Begin
    
                SET @SQLCommand = @BaseSQLCommand + @Where
                SELECT @CountCheck = 'update tempcount set rowsfound = (select count(*) '+ substring(@SQLCommand,10,len(@SQLCommand)) + ')'
                EXEC (@CountCheck) 
    
                if ((select rowsfound from tempcount) > 0)
                        Begin
                            PRINT '--- ['+cast(@NewMinID as varchar(15))+'/'+cast(@NewMaxID as varchar(15))+'] '+@Table + ' ----------------------------------[FOUND!]'
                            --PRINT '--- [FOUND USING:] ' +@SQLCommand
                            insert into @DataFoundInTables (sqlcmd) select @SQLCommand
                            EXEC (@SQLCommand) 
                            update tempcount set rowsfound = 0
                        End
                else
                        Begin
                            PRINT '--- ['+cast(@NewMinID as varchar(15))+'/'+cast(@NewMaxID as varchar(15))+'] '+@Table
                        End
                End
    
            SET @SCn = @SCn + 1
            End
    
        set @NewMinID = @NewMinID + 1
        end
    
    if ((select count(*) from sysobjects where name = 'tempcount') > 0)
        drop table tempcount
    
    /*
    
    This will now return all the sql commands you need to use
    
    */
    
    
    select @NewMinID = min(id), @NewMaxID = max(id) from @DataFoundInTables
    
    if (@NewMaxID > 0)
        Begin
        PRINT ' '   
        PRINT ' '   
        PRINT '-----------------------------------------'
        PRINT '----------- TABLES WITH DATA ------------'
        PRINT '-----------------------------------------'
        PRINT ' '   
        PRINT 'We found ' + cast(@NewMaxID as varchar(10)) + ' table(s) with the string '+@StringToFind
        PRINT ' '
    
        while(@NewMinID <= @NewMaxID)
            Begin
    
            select @SQLCommand = sqlcmd from @DataFoundInTables where ID = @NewMinID
    
            PRINT @SQLCommand
    
            SET @NewMinID = @NewMinID + 1
            End
    
        PRINT ' '   
        PRINT '-----------------------------------------'
    
        End
    
    • 1

relate perguntas

  • SQL Server - Como as páginas de dados são armazenadas ao usar um índice clusterizado

  • Preciso de índices separados para cada tipo de consulta ou um índice de várias colunas funcionará?

  • Quando devo usar uma restrição exclusiva em vez de um índice exclusivo?

  • Quais são as principais causas de deadlocks e podem ser evitadas?

  • Como determinar se um Índice é necessário ou necessário

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve