How can I search all columns in a table?

后端 未结 6 1443
天涯浪人
天涯浪人 2020-12-15 06:41

How can I search all columns of a table in SQL Server?

6条回答
  •  一个人的身影
    2020-12-15 07:08

    I can't take credit, but I found this and it works perfectly. You can add additional data types to the WHERE clause to include other types, as well as adding a schema name to the JOIN (commented below) to limit your search, if needed.

    DECLARE @SQL VARCHAR(MAX) 
    DECLARE @SearchString VARCHAR(100) 
    SET @SQL='' 
    
    -- ------------------------------------------ 
    -- Enter the string to be searched for here : 
    SET @SearchString='' 
    -- ------------------------------------------ 
    
    SELECT   @SQL = @SQL + 'SELECT CONVERT(VARCHAR(MAX),COUNT(*)) + '' matches in column ''+'''
         + C.name + '''+'' on table '' + ''' + SC.name + '.' + T.name + 
         ''' [Matches for '''+@SearchString+''':] FROM ' + 
         QUOTENAME(SC.name) + '.' + QUOTENAME(T.name) + ' WHERE ' + QUOTENAME(C.name) + 
         ' LIKE ''%' + @SearchString + 
         '%'' HAVING COUNT(*)>0 UNION ALL ' +CHAR(13) + CHAR(10) 
    
    FROM     sys.columns C 
    JOIN     sys.tables T ON C.object_id=T.object_id 
    JOIN     sys.schemas SC ON SC.schema_id=T.schema_id -- AND SC.name = ''
    JOIN     sys.types ST ON C.user_type_id=ST.user_type_id 
    JOIN     sys.types SYST ON ST.system_type_id=SYST.user_type_id
        AND ST.system_type_id=SYST.system_type_id 
    
    WHERE    SYST.name IN ('varchar','nvarchar','text','ntext','char','nchar') 
    
    ORDER BY T.name, C.name 
    
    -- Strip off the last UNION ALL 
    
    IF LEN(@SQL)>12 
      SELECT @SQL=LEFT(@SQL,LEN(@SQL)- 12) 
    
    EXEC(@SQL) 
    --PRINT @SQL
    

    Reference: https://www.sqlmatters.com/Articles/Searching%20all%20columns%20in%20all%20tables%20in%20a%20database.aspx

提交回复
热议问题