Search code examples
sql-serversql-server-2000

Searching for a string in all tables of database in SQL Server 2000


There are many answers in many places about this question, such as:

Search for a string in all tables, rows and columns of a DB

However I am using SQL Server 2000 and need to do the same thing: search all tables in a database for a specific string.


Solution

  • DECLARE @SearchString VARCHAR(32);
    SET @SearchString = 'Something';
    
    CREATE TABLE #results(o NVARCHAR(512), c SYSNAME, value NVARCHAR(4000));
    
    DECLARE @sql NVARCHAR(4000), @o NVARCHAR(512), @c SYSNAME;
    
    DECLARE c CURSOR LOCAL FAST_FORWARD FOR 
       SELECT QUOTENAME(u.name) + '.' + QUOTENAME(o.name), QUOTENAME(c.name)
    FROM sysobjects AS o
    INNER JOIN syscolumns AS c ON o.id = c.id
    INNER JOIN sysusers AS u ON o.uid = u.uid
    WHERE c.xtype IN (35, 99, 167, 175, 231, 239) AND o.xtype = 'U';
    
    OPEN c;
    
    FETCH c INTO @o, @c;
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
      SET @sql = N'INSERT #Results(o,c,value) SELECT @o, @c, 
        CONVERT(NVARCHAR(4000), ' + @c + ') FROM ' + @o + ' WHERE ' 
        + @c + ' LIKE ''%' + @SearchString + '%'';';
      EXEC sp_executesql @sql, N'@o NVARCHAR(512), @c SYSNAME', @o, @c;
      FETCH c INTO @o, @c;
    END
    
    CLOSE c;
    DEALLOCATE c;
    
    SELECT o, c, value FROM #Results;
    
    DROP TABLE #Results;