如何在数据库中搜索文本字符串?

时间:2013-06-18 11:54:54

标签: sql-server search

有没有办法在整个SQL Server数据库中搜索文本字符串?

通过整个数据库我指的是表,视图,存储过程等。

3 个答案:

答案 0 :(得分:2)

如果通过数据库,确实意味着包括过程源代码在内的所有内容,最简单的可能是生成数据库转储并在结果文件中搜索字符串。这比在信息模式上运行各种查询更简单。

答案 1 :(得分:1)

以下是搜索存储过程中某些文本的代码

SELECT Distinct SO.Name
FROM sysobjects SO (NOLOCK)
INNER JOIN syscomments SC (NOLOCK) on SO.Id = SC.ID
AND SO.Type = 'P'
AND SC.Text LIKE '%test%'
ORDER BY SO.Name

答案 2 :(得分:0)

我得到了一个解决方案,用存储过程显示/搜索所有表,列和SP:

CREATE PROC SearchAllTables 
(
@SearchStr nvarchar(100)
)
AS
BEGIN

-- Copyright © 2013 Peter Nold. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string

CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110), @myCount varchar(255)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

/* debug */
print '************************************************************'
print 'Starting Search For: ' + @SearchStr2
print '************************************************************'

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 QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN

            -- debug
            print 'Searching the field: ' + @TableName + '.' + @ColumnName

            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(CONVERT(varchar(max), ' + @ColumnName + '), 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE CONVERT(varchar(max), ' + @ColumnName + ') LIKE ' + @SearchStr2
            )
        END
    END 
END

SELECT ColumnName, ColumnValue FROM #Results

SET @myCount = 'Found in #columns: ' + cast((select count(*) from #Results) AS VARCHAR)
print '************************************************************'
print @myCount
print '************************************************************'

END

/* example to search for the text METZ:
 ***
exec SearchAllTables 'METZ'
*/