1

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.

4

1 回答 1

1
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;
于 2013-02-20T15:43:15.567 回答