Thursday, August 27, 2015

Search String in all tables Sql Server

Anonymous block which can search any string from all tables. This block is SQL Server specific.

declare @SearchString nvarchar(100);
SET @SearchString = 'any string want to search';
BEGIN
 IF OBJECT_ID('tempdb..#StrResults') IS NOT NULL DROP TABLE #StrResults
    CREATE TABLE #StrResults (ColumnName nvarchar(100), ColumnValue nvarchar(500))

    SET NOCOUNT ON

    DECLARE @TableName nvarchar(100), @ColumnName nvarchar(100), @SearchString2 nvarchar(100)
    SET  @TableName = ''
    SET @SearchString2 = QUOTENAME('%' + @SearchString + '%','''')

    WHILE @TableName IS NOT NULL

    BEGIN
        SET @ColumnName = ''
        SET @TableName = 
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM     INFORMATION_SCHEMA.TABLES
            WHERE         TABLE_TYPE = 'BASE TABLE'
                AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                AND    OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA)
      + '.' +
      QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
        )

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM     INFORMATION_SCHEMA.COLUMNS
                WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                    AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                    AND    QUOTENAME(COLUMN_NAME) > @ColumnName
            )

            IF @ColumnName IS NOT NULL

            BEGIN
                INSERT INTO #StrResults
                EXEC
                (
                    'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 500) 
                    FROM ' + @TableName + 'WITH (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchString2
                )
            END
        END    
    END

    SELECT ColumnName, ColumnValue FROM #StrResults
END


To make above Anonymous block as named procedure just replace first two lines of procedure with below lines:



CREATE PROC search_string
(
@SearchString nvarchar(100)
)
AS



1 comment:

  1. Search String in All Databases all tables

    source
    https://www.mssqltips.com/sqlservertip/4039/search-all-string-columns-in-all-sql-server-databases/


    CREATE PROCEDURE dbo.SearchAllDatabases
    @SearchTerm NVARCHAR(255) = NULL
    AS
    BEGIN
    SET NOCOUNT ON;
    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

    IF @SearchTerm IS NULL OR @SearchTerm NOT LIKE N'%[^%^_]%'
    BEGIN
    RAISERROR(N'Please enter a valid search term.', 11, 1);
    RETURN;
    END

    CREATE TABLE #results
    (
    [database] SYSNAME,
    [schema] SYSNAME,
    [table] SYSNAME,
    [column] SYSNAME,
    ExampleValue NVARCHAR(1000)
    );

    DECLARE
    @DatabaseCommands NVARCHAR(MAX) = N'',
    @ColumnCommands NVARCHAR(MAX) = N'';

    SELECT *
    @DatabaseCommands = @DatabaseCommands
    +
    N'EXEC ' + QUOTENAME(name) + '.sys.sp_executesql @ColumnCommands, N''@SearchTerm NVARCHAR(MAX)'', @SearchTerm;'
    FROM sys.databases
    WHERE database_id > 4 -- non-system databases
    AND [state] = 0 -- online
    AND user_access = 0; -- multi-user

    SET @ColumnCommands =
    N'
    DECLARE @q NCHAR(1), @SearchCommands NVARCHAR(MAX);

    SELECT
    @q = NCHAR(39),
    @SearchCommands = N''DECLARE @VSearchTerm VARCHAR(255) = @SearchTerm;'';

    SELECT @SearchCommands = @SearchCommands + CHAR(10) + N''

    SELECT TOP (1)
    [db] = DB_NAME(),
    [schema] = N'' + @q + s.name + @q + '',
    [table] = N'' + @q + t.name + @q + '',
    [column] = N'' + @q + c.name + @q + '',
    ExampleValue = LEFT('' + QUOTENAME(c.name) + '', 1000)
    FROM '' + QUOTENAME(s.name) + ''.'' + QUOTENAME(t.name) + ''
    WHERE '' + QUOTENAME(c.name) + N'' LIKE @'' + CASE WHEN c.system_type_id IN (35, 167, 175,231) THEN ''V'' ELSE '''' END + ''SearchTerm;''

    FROM sys.schemas AS s
    INNER JOIN sys.tables AS t
    ON s.[schema_id] = t.[schema_id]
    INNER JOIN sys.columns AS c
    ON t.[object_id] = c.[object_id]
    WHERE c.system_type_id IN (35, 167, 175, 231)
    AND c.max_length >= LEN(@SearchTerm);

    PRINT @SearchCommands;
    EXEC sys.sp_executesql @SearchCommands,
    N''@SearchTerm NVARCHAR(255)'', @SearchTerm;';

    INSERT #Results
    (
    [database],
    [schema],
    [table],
    [column],
    ExampleValue
    )
    EXEC [master].sys.sp_executesql @DatabaseCommands,
    N'@ColumnCommands NVARCHAR(MAX), @SearchTerm NVARCHAR(255)',
    @ColumnCommands, @SearchTerm;

    SELECT [Searched for] = @SearchTerm;

    SELECT [database],[schema],[table],[column],ExampleValue
    FROM #Results
    ORDER BY [database],[schema],[table],[column];
    END
    GO


    EXEC dbo.SearchAllDatabases @SearchTerm = N'++';

    ReplyDelete

web stats