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



No comments:

Post a Comment

web stats