简体   繁体   中英

Search for a value in all column and all tables of a database

I want to find the column name that contain the value "Commerciale", but i do not know the column name or the table so I need to search in the whole database. How can i do that with a query?

I'm using SQL SERVER

you can use system tables:

SELECT 
    c.name ColumnName
 , t.name TableName
FROM sys.columns AS c
JOIN sys.tables AS t
ON c.object_id = t.object_id
WHERE c.name like '%Commerciale%'

If you are looking for columns where the name is Commerciale then you can simply use the sys objects:

SELECT s.[name] AS SchemaName,
       t.[name] AS TableName,
       c.[name] AS ColumnName
FROM sys.schemas s
     JOIN sys.tables t ON s.schema_id = t.schema_id
     JOIN sys.columns c ON t.object_id = c.object_id
WHERE c.[name] = N'Commerciale';

If, however, you need to search the contents of the values in the rows, you'll need to use dynamic SQL. This will return a dataset for every table in your database which has at least 1 string type column, and will return any rows where the value of one of those columns has the value 'Commerciale' . If it needs to contain the value, change the WHERE to use a LIKE in it's clauses instead (note the query will be horrifically slow with that):

DECLARE @SQL nvarchar(MAX),
        @CRLF nchar(2) = NCHAR(13) + NCHAR(10);

SET @SQL = STUFF((SELECT @CRLF +
                         N'SELECT N' + QUOTENAME(s.[name],'''') + N' AS SchemaName,' + @CRLF +
                         N'       N' + QUOTENAME(t.[name],'''') + N' AS TableName,' + @CRLF +
                         N'       *' + @CRLF +
                         N'FROM ' + QUOTENAME(s.[name]) + N'.' + QUOTENAME(t.[name]) + @CRLF + 
                         N'WHERE ' +
                         STUFF((SELECT @CRLF +
                                       N'  AND ' + QUOTENAME(c.[name]) + N' = ''Commerciale'''
                                FROM sys.columns c
                                     JOIN sys.types ct ON c.system_type_id = ct.system_type_id
                                WHERE c.object_id = t.object_id
                                  AND ct.[name] IN (N'char',N'varchar',N'nchar',N'nvarchar')
                                FOR XML PATH(''),TYPE).value('(./text())[1]','nvarchar(MAX)'),1,8,N'') + N';'
                  FROM sys.schemas s
                       JOIN sys.tables t ON s.schema_id = t.schema_id
                  FOR XML PATH(''),TYPE).value('(./text())[1]','nvarchar(MAX)'),1,2,N'');

--PRINT @SQL; --YOu best friend

EXEC sp_executesql @SQL;

This won't tell you what column has the value, you'll need to use your own eyes to do that, but I wasn't entertaining writing a dynamic table dynamic pivot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM