如何使用行值获取表名?

时间:2018-03-27 10:11:58

标签: sql

SELECT name FROM sysobjects 
WHERE id IN ( SELECT id FROM syscolumns WHERE name like 'order_id')

使用列名称获取表名。

是否可以使用行值获取表名,就像我有一个表顺序包含orderid一样,使用orderid值是否可以在数据库中获取表名

1 个答案:

答案 0 :(得分:0)

不幸的是,我不得不做类似的事情。这是我使用的脚本(如果您使用的是SQL Server)。

请注意,这将需要很长时间,具体取决于您的数据库。您可以通过查看游标上的查询来随意限制表或模式。您也可以对其进行编辑,以进行LIKE搜索,而不是相等(=)。如果您有BLOB或其他无法与字符串比较的数据类型,它可能还需要按列类型进行过滤。

DECLARE @v_TextToSearch VARCHAR(100) = 'YourSearchValue'


IF OBJECT_ID('tempdb..#FoundColumns') IS NOT NULL
    DROP TABLE #FoundColumns

CREATE TABLE #FoundColumns (
    SchemaName VARCHAR(200),
    TableName VARCHAR(200),
    ColumnName VARCHAR(200))


DECLARE @c_SchemaName VARCHAR(200)
DECLARE @c_TableName VARCHAR(200)

DECLARE TableCursor CURSOR FOR
    SELECT
        SchemaName = QUOTENAME(SCHEMA_NAME(T.schema_id)),
        TableName = QUOTENAME(T.name)
    FROM
        sys.tables AS T
    ORDER BY
        1,
        2

OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @c_SchemaName, @c_TableName

WHILE @@FETCH_STATUS = 0
BEGIN

    DECLARE @c_ColumnName VARCHAR(200)

    DECLARE ColumnCursor CURSOR FOR
        SELECT
            ColumnName = QUOTENAME(C.name)
        FROM
            sys.tables AS T
            INNER JOIN sys.columns AS C ON C.object_id = T.object_id
        WHERE
            QUOTENAME(SCHEMA_NAME(T.schema_id)) = @c_SchemaName AND
            QUOTENAME(T.name) = @c_TableName
        ORDER BY
            C.name

    OPEN ColumnCursor
    FETCH NEXT FROM ColumnCursor INTO @c_ColumnName

    WHILE @@FETCH_STATUS = 0
    BEGIN

        DECLARE @v_DynamicSQLInsert VARCHAR(MAX) = '

            INSERT INTO #FoundColumns (
                SchemaName,
                TableName,
                ColumnName)
            SELECT
                SchemaName = ''' + @c_SchemaName + ''',
                TableName = ''' + @c_TableName + ''',
                ColumnName = ''' + @c_ColumnName + ''' 
            WHERE
                EXISTS (
                    SELECT
                        1
                    FROM
                        ' + @c_SchemaName + '.' + @c_TableName + ' AS T
                    WHERE
                        CONVERT(VARCHAR(8000), T.' + @c_ColumnName + ') = ''' + @v_TextToSearch + ''')'

        EXEC (@v_DynamicSQLInsert)

        FETCH NEXT FROM ColumnCursor INTO @c_ColumnName

    END

    CLOSE ColumnCursor
    DEALLOCATE ColumnCursor 

    FETCH NEXT FROM TableCursor INTO @c_SchemaName, @c_TableName

END

CLOSE TableCursor
DEALLOCATE TableCursor


SELECT
    F.SchemaName,
    F.TableName,
    F.ColumnName
FROM
    #FoundColumns AS F
ORDER BY
    F.SchemaName,
    F.TableName,
    F.ColumnName