Saturday, January 12, 2008

A T-SQL script to search all the columns in a database for a given string

This T-SQL script lets you search through all the columns (nchar, nvarchar, ntext) in a MS-SQL Server database for a given string. Simply change the DbName to your database name and set the @SearchValue to the string you want to search for. The script will return a resultset for each hit, with tablename, column where it found the search-string and all the other columns in that row.

Here's the code:


-- Change the name below to the database you want to search in.
use dbname;

set nocount on;

declare @TableName nvarchar(200)
declare @SchemaName nvarchar(200)
declare @ColumnName nvarchar(200)
declare @Sql nvarchar(4000)
declare @SearchValue nvarchar(200)
declare @Count int

-- Change the value below to the value to search for.
set @SearchValue = '%searchstring%'

-- Get a list of schema, table, column.
DECLARE Items

CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
select s.Name as SchemaName, t.name as TableName, c.name as ColumnName
from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.columns c on t.object_id = c.object_id
where c.user_type_id in (167, 175, 239, 99, 35, 231)
OPEN Items
FETCH NEXT FROM Items
INTO @SchemaName, @TableName, @ColumnName

WHILE (@@FETCH_STATUS = 0)
BEGIN
 -- Execute a count(*) select in order to only return results with 1 or more hits.
 set @Sql = 'select @Count = count(*) from [' + @SchemaName + '].[' +  @TableName + '] where [' + @ColumnName + '] like ''' + @SearchValue + ''';'

 exec sp_executesql @sql, N'@Count int output', @Count output

 if @Count > 0
  begin
   -- Return result with tablename, hit column, * columns.
   set @Sql = 'select ''' + @TableName + ''' as TableName, ' + @ColumnName + ', *'
   set @Sql = @Sql + ' from [' + @SchemaName + '].[' + @TableName + ']'
   set @Sql = @Sql + ' where [' + @ColumnName + '] like ''' + @SearchValue + ''';'
   execute sp_executesql @sql
  end

  FETCH NEXT FROM Items
  INTO @SchemaName, @TableName, @ColumnName
 END
END

CLOSE Items
DEALLOCATE Items