Mysql query search a string in all columns of a table

后端 未结 4 1354
一向
一向 2021-01-27 11:43

I wonder how I can mount a SQL as portable as possible to query for all columns of a table for a specific phrase, like:

Table

ID | Name          


        
4条回答
  •  余生分开走
    2021-01-27 12:14

    you can use this store procedure to search a text in all column in table

    CREATE PROCEDURE dbo.sp_FindStringInTable @stringToFind VARCHAR(100), 
    @schema 
    sysname, @table sysname 
    AS
    
    BEGIN TRY
    DECLARE @sqlCommand varchar(max) = 'SELECT * FROM [' + @schema + '].[' + 
    @table + '] WHERE ' 
    
    SELECT @sqlCommand = @sqlCommand + '[' + COLUMN_NAME + '] LIKE ''' + 
    @stringToFind + ''' OR '
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = @schema
    AND TABLE_NAME = @table 
    AND DATA_TYPE IN ('char','nchar','ntext','nvarchar','text','varchar')
    
    SET @sqlCommand = left(@sqlCommand,len(@sqlCommand)-3)
    EXEC (@sqlCommand)
    PRINT @sqlCommand
    END TRY
    
    BEGIN CATCH 
    PRINT 'There was an error. Check to make sure object exists.'
    PRINT error_message()
    END CATCH 
    

    Execute it like this

    EXEC sp_FindStringInTable '%searchword%','schema_name', 'tablename'
    

提交回复
热议问题