/*============================================================================= 

Search for a given text in all varchar / nvarchar / text / ntext fields in the current db
Derived from https://social.technet.microsoft.com/wiki/contents/articles/24169.sql-server-searching-all-columns-in-a-table-for-a-string.aspx

Creation : 28.12.2022 / TSC
Modifications:

=============================================================================*/ 
--#region setup
IF OBJECT_ID('TempDB..#Result', N'U') IS NOT NULL 
    DROP TABLE #Result;

CREATE TABLE #RESULT ([PK COLUMN] NVARCHAR(MAX), [COLUMN VALUE] NVARCHAR(MAX), [COLUMN Name] sysname, [TABLE SCHEMA] sysname, [TABLE Name] sysname);
DECLARE @Table_Name sysname, @SearchString NVARCHAR(MAX), @Table_Schema sysname;
DECLARE @Columns NVARCHAR(MAX), @Cols NVARCHAR(MAX), @PkColumn NVARCHAR(MAX);
--#endregion
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SET @SearchString = N'49300';

DECLARE curAllTables CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
    SELECT   [TABLE_SCHEMA], [TABLE_NAME]
        FROM [INFORMATION_SCHEMA].[TABLES]   
    WHERE [TABLE_TYPE] = 'BASE TABLE'
    ORDER BY [TABLE_SCHEMA], [TABLE_NAME];
     
    OPEN curAllTables;
    FETCH  curAllTables
    INTO @Table_Schema, @Table_Name;   
    WHILE (@@FETCH_STATUS = 0)
    BEGIN

        -- Get all character columns
        SET @Columns = STUFF((SELECT ', ' + QUOTENAME([COLUMN_NAME])
         FROM [INFORMATION_SCHEMA].[COLUMNS]
         WHERE [DATA_TYPE] IN ('text','ntext','varchar','nvarchar','char','nchar')
         AND [TABLE_NAME] = @Table_Name AND [TABLE_SCHEMA] = @Table_Schema
         ORDER BY [COLUMN_NAME]
         FOR XML PATH('')),1,2,'');
  
        IF @Columns IS NOT NULL 
        BEGIN 
  
            -- Get columns for select statement - we need to convert all columns to nvarchar(max)
            SET @Cols = STUFF((SELECT ', CAST(' + QUOTENAME([COLUMN_NAME]) + ' AS nvarchar(max)) COLLATE DATABASE_DEFAULT AS ' + QUOTENAME([COLUMN_NAME])
            FROM [INFORMATION_SCHEMA].[COLUMNS]
            WHERE [DATA_TYPE] IN ('text','ntext','varchar','nvarchar','char','nchar')
              AND [TABLE_NAME] = @Table_Name AND [TABLE_SCHEMA] = @Table_Schema
            ORDER BY [COLUMN_NAME]
            FOR XML PATH('')),1,2,'');
   
            SET @PkColumn = STUFF((SELECT N' + ''|'' + ' + ' CAST(' + QUOTENAME(CU.[COLUMN_NAME]) + ' AS nvarchar(max)) COLLATE DATABASE_DEFAULT '
  
            FROM [INFORMATION_SCHEMA].[TABLE_CONSTRAINTS] AS TC
                INNER JOIN [INFORMATION_SCHEMA].[KEY_COLUMN_USAGE] AS CU
                    ON TC.[CONSTRAINT_TYPE] = 'PRIMARY KEY' 
                   AND TC.[CONSTRAINT_NAME] = CU.[CONSTRAINT_NAME]
            WHERE TC.[TABLE_SCHEMA] = @Table_Schema 
              AND TC.[TABLE_NAME] = @Table_Name
            ORDER BY CU.[ORDINAL_POSITION]
            FOR XML PATH('')),1,9,'');
  
            IF @PkColumn IS NULL
                SELECT @PkColumn = 'CAST(NULL AS nvarchar(max))';
            -- set select statement using dynamic UNPIVOT
            DECLARE @SQL NVARCHAR(MAX);
            SET @SQL = '
INSERT #RESULT ([PK COLUMN], [Column Value], [Column Name], [Table Schema], [Table Name])
SELECT unpvt.[PK Column]
    , unpvt.[Column Value]
    , unpvt.[Column Name]
    , ' + QUOTENAME(@Table_Schema,'''') + ' AS [Table Schema]
    , ' + QUOTENAME(@Table_Name,'''') + ' AS [Table Name]
FROM (
    SELECT '+ @PkColumn + ' AS [PK Column]
        , ' + @Cols + ' 
    FROM ' + QUOTENAME(@Table_Schema) + '.' + QUOTENAME(@Table_Name) +  ' ) src 
        UNPIVOT ([Column Value] for [Column Name] IN (' + @Columns + ')
) unpvt
WHERE [Column Value] LIKE ''%'' + @SearchString + ''%'';

';
   
            --print @SQL
            EXECUTE sp_ExecuteSQL @SQL, N'@SearchString nvarchar(max)', @SearchString;
        END; 

        FETCH  curAllTables
        INTO @Table_Schema, @Table_Name;
      END; -- while
    CLOSE curAllTables;
    DEALLOCATE curAllTables;
  
  -- Return results
  SELECT * FROM #RESULT ORDER BY [Table Name];

GO
 