find column name or table name of a specific value

女生的网名这么多〃 提交于 2019-12-26 07:42:47

问题


I want search a specific value in my database that i don't know where is it exactly. Is there any query exist that returned column name or table name of a specific value in SQL server? Assume that I have a value of a column like 123, but I don't know 123 belongs to which table and I don't know any about its column name. Can i write a query to find table names that this value is in it? I need a query not a procedure!!!


回答1:


This might do it for you. Note that if you have a lot of tables/columns this might take quite a while. If you're not searching in (N)VARCHAR columns, you might want to add those types to the c.DATA_TYPE NOT IN(... clause. Or any other type you're not looking in (like FLOAT or DECIMAL).

SET NOCOUNT ON;
DECLARE @value NVARCHAR(MAX)='123';
CREATE TABLE #found(table_name SYSNAME,column_name SYSNAME);
DECLARE @sql NVARCHAR(MAX)=(
    SELECT
        'INSERT INTO #found(table_name,column_name) ' +
        'SELECT TOP 1 '+
            'table_name='''+REPLACE(t.TABLE_NAME,'''','''''')+''','+
            'column_name='''+REPLACE(c.COLUMN_NAME,'''','''''')+''' '+
        'FROM '+
            QUOTENAME(t.TABLE_SCHEMA)+'.'+QUOTENAME(t.TABLE_NAME)+' '+
        'WHERE '+
            QUOTENAME(c.COLUMN_NAME)+'='''+REPLACE(@value,'''','''''')+''';'
    FROM
        INFORMATION_SCHEMA.TABLES AS t
        INNER JOIN INFORMATION_SCHEMA.COLUMNS AS c ON
            c.TABLE_SCHEMA=t.TABLE_SCHEMA AND
            c.TABLE_NAME=t.TABLE_NAME
    WHERE
        t.TABLE_TYPE='BASE TABLE' AND 
        c.DATA_TYPE NOT IN('BIT','NTEXT','TEXT','IMAGE','BINARY','VARBINARY','DATETIME','DATE','DATETIME2','TIME','SMALLDATETIME','DATETIMEOFFSET')
    FOR XML
        PATH('')
);

EXECUTE (@sql);
SELECT * FROM #found ORDER BY table_name,column_name;
DROP TABLE #found;


来源:https://stackoverflow.com/questions/40479193/find-column-name-or-table-name-of-a-specific-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!