找到一个值并显示找到的值的数据库,表,列,主键

时间:2017-04-13 06:57:32

标签: sql sql-server database tsql search

考虑使用名为:People

的表
| Id    | Name    | Code   |
| 1     | John    | 857    |
| 2     | Mike    | 893    |
| 3     | Sara    | 935    |

此表位于PeopleDb表中。

问题是:

我想找到'Mike'关键字。 情况: 我不知道在哪个数据库中搜索表。

我需要一个搜索所有数据库和表格的T-sql查询,并向我显示:

| Id  | DatabaseName  | TableName  | ColumnName  | Pk  | SearchValue
| 1   | 'PeopleDb'    | 'People'   | 'Name'      | 2   | 'Mike'

我不知道如何编写查询以在所有数据库和表中进行搜索。

非常感谢任何帮助。

编辑:

速度不是问题,我需要这样做。

我尝试了这个查询,我想要相同但搜索所有数据库。

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

-- Copyright © 2002 Narayana Vyas Kondreddi.All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT

DECLARE @Results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

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

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

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END
END

SELECT ColumnName, ColumnValue FROM @Results
END

更新:

我需要一个可以工作的T-Sql来搜索所有数据库,表,列,所有类型的变量。 当前的答案在某些情况下不起作用,例如nvarchar字段中的连接字符串。

4 个答案:

答案 0 :(得分:2)

我已按照以下更新了您的逻辑,它运行正常,请看一下:

DECLARE @SearchStr VARCHAR(50)='Surat'

DECLARE @Results TABLE(DatabaseName NVARCHAR(500),  TableName nvarchar(370),ColumnName nvarchar(370), ColumnValue nvarchar(3630),PrimaryKey nvarchar(200), PrimaryKeyValue nvarchar(4000))

SET NOCOUNT ON

DECLARE @TableList AS Table
(
    TableName VARCHAR(500),
    RowNo INT
)

DECLARE @ColumnList AS Table
(
    ColumnName VARCHAR(500),
    RowNo INT
)

DECLARE @PrimaryKeyList AS Table
(
    PrimaryKeyName VARCHAR(500)
)

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110), @PrimaryKey nvarchar(200), @CurrentTableName nvarchar(256)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%', '''')

DECLARE @DatabaseCount INT=0, @Index INT=0, @DatabaseName NVARCHAR(500), @TotalColumnCount INT, @ColumnIndex INT=0, @TotalTableCount INT, @TableIndex INT=0

SELECT 
    *,
    ROW_NUMBER() OVER (ORDER BY name) AS RowNo 
INTO #tblDatabases 
FROM Sys.Databases
WHERE name NOT IN ('master','model','msdb','tempdb')

SELECT @DatabaseCount=COUNT (*) FROM #tblDatabases
WHILE @Index<@DatabaseCount
BEGIN
    SET @Index=@Index+1
    SELECT @DatabaseName='',@TableIndex=0,@ColumnIndex=0,@TableName='',@ColumnName=''
    SELECT @DatabaseName=name FROM #tblDatabases WHERE RowNo=@Index     

    DELETE FROM @TableList
    INSERT INTO @TableList
    EXEC('
            SELECT QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME),
                ROW_NUMBER() OVER (ORDER BY TABLE_NAME)
            FROM ['+@DatabaseName+'].INFORMATION_SCHEMA.TABLES
            WHERE TABLE_TYPE = ''BASE TABLE''
        ')

    SELECT @TotalTableCount=COUNT(*) FROM @TableList

    WHILE @TableIndex<@TotalTableCount 
    BEGIN   

        SET @TableIndex=@TableIndex+1
        SELECT @ColumnName = '',@ColumnIndex=0

        SELECT @TableName=TableName FROM @TableList  WHERE RowNo=@TableIndex            
        SET @CurrentTableName=REPLACE(REPLACE(REPLACE(@TableName,'[dbo].',''),'[',''),']','')

        DELETE FROM @ColumnList
        INSERT INTO @ColumnList
        EXEC('SELECT
                COLUMN_NAME,ROW_NUMBER() OVER (ORDER BY COLUMN_NAME)
                    FROM ['+@DatabaseName+'].INFORMATION_SCHEMA.COLUMNS
                WHERE TABLE_SCHEMA = PARSENAME('''+@TableName+''', 2)
                    AND TABLE_NAME = PARSENAME('''+@TableName+''', 1)
                    AND DATA_TYPE IN (''char'', ''varchar'', ''nchar'', ''nvarchar'')


        ')

        SELECT @TotalColumnCount=COUNT(*) FROM @ColumnList

        WHILE @ColumnIndex<@TotalColumnCount
        BEGIN
            SET @ColumnIndex=@ColumnIndex+1
            SET @ColumnName=''
            SELECT @ColumnName=ColumnName FROM @ColumnList WHERE RowNo=@ColumnIndex         

            DELETE FROM @PrimaryKeyList
            INSERT INTO @PrimaryKeyList
            EXEC('
                    SELECT Col.Column_Name from 
                        ['+@DatabaseName+'].INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, 
                        ['+@DatabaseName+'].INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col 
                    WHERE 
                        Col.Constraint_Name = Tab.Constraint_Name
                        AND Col.Table_Name = Tab.Table_Name
                        AND Constraint_Type = ''PRIMARY KEY''
                        AND Col.Table_Name= '''+@CurrentTableName+'''           
                ')

            SELECT @PrimaryKey=''
            SELECT @PrimaryKey=PrimaryKeyName FROM @PrimaryKeyList
            SET @PrimaryKey=ISNULL(@PrimaryKey,'')

            IF @ColumnName IS NOT NULL AND @PrimaryKey<>''
            BEGIN   
                INSERT INTO @Results
                EXEC
                (
                    'SELECT '''+@DatabaseName+''','''+@CurrentTableName+''',''' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) , '''+@PrimaryKey+''', [' + @PrimaryKey + '] 
                    FROM ['+@DatabaseName+'].' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END
    END
END


SELECT ROW_NUMBER() OVER (ORDER BY DatabaseName) AS Id,DatabaseName,TableName,ColumnName, ColumnValue AS SearchValue,PrimaryKeyValue AS Pk, PrimaryKey  FROM @Results

DROP TABLE #tblDatabases

答案 1 :(得分:1)

SELECT * FROM all_objects where object_name = 'XXXX';

答案 2 :(得分:0)

这似乎是一件疯狂的事情 - 搜索可能完全杀死你的服务器。也就是说,如果这是一次性/偶尔使用手册运行的事情,那么您可以创建一个脚本来生成所需的SQL命令,然后执行结果集。在重构数据库中的列之前,我已经完成了这类工作。 您的脚本需要首先运行查询以获取sql-server实例上所有数据库的名称

  SELECT * FROM sys.databases

然后创建动态sql,包括USE命令以指定数据库,并使用information_schema.tables和.columns获取要搜索的所有表和列的名称 - 由您决定如何选择列到被搜索(例如,它只是N&#39;%name%&#39;等列。

然后在for循环中使用此信息来创建单个表/列搜索。为了提高效率(并且如果它不能正常工作,可以帮助你进行调试)我建议使用@table变量。

最后选择包含您已创建的表格查询的任何@tables的内容。

然后可以在服务器上运行此输出 - 前提是您已将使用命令或带有[dbname]。[schema]的前缀表名称包括在内。

答案 3 :(得分:0)

您可以使用此商店程序

    CREATE PROCEDURE dbo.SearchAllDatabases
  @SearchTerm NVARCHAR(255) = NULL
AS
BEGIN
  SET NOCOUNT ON;
  SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

  IF @SearchTerm IS NULL OR @SearchTerm NOT LIKE N'%[^%^_]%'
  BEGIN
    RAISERROR(N'Please enter a valid search term.', 11, 1);
    RETURN;
  END

  CREATE TABLE #results
  (
    [database]   SYSNAME,
    [schema]     SYSNAME,
    [table]      SYSNAME, 
    [column]     SYSNAME,
    ExampleValue NVARCHAR(1000)
  );

  DECLARE
    @DatabaseCommands  NVARCHAR(MAX) = N'', 
    @ColumnCommands    NVARCHAR(MAX) = N'';

  SELECT @DatabaseCommands = @DatabaseCommands + N'
    EXEC ' + QUOTENAME(name) + '.sys.sp_executesql 
        @ColumnCommands, N''@SearchTerm NVARCHAR(MAX)'', @SearchTerm;'
    FROM sys.databases 
    WHERE database_id  > 4  -- non-system databases  
      AND [state]      = 0  -- online 
      AND user_access  = 0; -- multi-user

    SET @ColumnCommands = N'DECLARE @q NCHAR(1),
          @SearchCommands NVARCHAR(MAX);

    SELECT @q = NCHAR(39), 
      @SearchCommands = N''DECLARE @VSearchTerm VARCHAR(255) = @SearchTerm;'';

    SELECT @SearchCommands = @SearchCommands + CHAR(10) + N''

      SELECT TOP (1)
        [db]     = DB_NAME(),
        [schema] = N'' + @q + s.name + @q + '', 
        [table]  = N'' + @q + t.name + @q + '',
        [column] = N'' + @q + c.name + @q + '',
        ExampleValue = LEFT('' + QUOTENAME(c.name) + '', 1000) 
      FROM '' + QUOTENAME(s.name) + ''.'' + QUOTENAME(t.name) + ''
      WHERE '' + QUOTENAME(c.name) + N'' LIKE @'' + CASE 
        WHEN c.system_type_id IN (35, 167, 175) THEN ''V'' 
        ELSE '''' END + ''SearchTerm;'' 

    FROM sys.schemas AS s
    INNER JOIN sys.tables AS t
    ON s.[schema_id] = t.[schema_id]
    INNER JOIN sys.columns AS c
    ON t.[object_id] = c.[object_id]
    WHERE c.system_type_id IN (35, 99, 167, 175, 231, 239)
      AND c.max_length >= LEN(@SearchTerm);

    PRINT @SearchCommands;
    EXEC sys.sp_executesql @SearchCommands, 
      N''@SearchTerm NVARCHAR(255)'', @SearchTerm;';

  INSERT #Results
  (
    [database],
    [schema],
    [table],
    [column],
    ExampleValue
  )
  EXEC [master].sys.sp_executesql @DatabaseCommands, 
    N'@ColumnCommands NVARCHAR(MAX), @SearchTerm NVARCHAR(255)', 
    @ColumnCommands, @SearchTerm;

  SELECT [Searched for] = @SearchTerm;

  SELECT [database],[schema],[table],[column],ExampleValue 
    FROM #Results 
    ORDER BY [database],[schema],[table],[column];
END
GO