开发者

Searching for particular value of a column

开发者 https://www.devze.com 2023-03-29 14:46 出处:网络
I want to query for a particular value lets say \"AYX\" in some particular column of some particular table in a database.I need to get the list of tables and columns basically having value as \"AYX\".

I want to query for a particular value lets say "AYX" in some particular column of some particular table in a database.I need to get the list of tables and columns basically having value as "AYX"..How do I go for it?Is it开发者_JS百科 possible? I am using SQL SERVER 2008


DECLARE @string NVARCHAR(32) = N'AYX';


CREATE TABLE #results
(
    [column] NVARCHAR(768), 
    [value] NVARCHAR(MAX)
);

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += 'SELECT ''' 
    +  QUOTENAME(OBJECT_SCHEMA_NAME([object_id])) 
    + '.' + QUOTENAME(OBJECT_NAME([object_id])) 
    + '.' + QUOTENAME(name) + ''', ' + QUOTENAME(name) + ' FROM ' 
    + QUOTENAME(OBJECT_SCHEMA_NAME([object_id])) 
    + '.' + QUOTENAME(OBJECT_NAME([object_id])) 
    + ' WHERE ' + QUOTENAME(name) + ' LIKE ''%' + @string + '%'';
    '
FROM sys.columns 
WHERE system_type_id IN (35, 99, 167, 175, 231, 239)
AND OBJECTPROPERTY([object_id], 'IsMsShipped') = 0;

INSERT #results EXEC sp_executesql @sql;

SELECT [column],[value] FROM #results;

DROP TABLE #results;


@Aaron Bertrand had a very nice script.

I just want to point out that there is a free tool SSMS Tools Pack can search data in all table/views.

SSMS Tools Pack


You'll need to use dynamic/code generated query.

Have a look at SELECT * FROM INFORMATION_SCHEMA.COLUMNS to get your list of columns in the database.

Restrict to appropriate datatypes with a WHERE clause on that table/view.

Code generate the queries to do the search: SELECT '{TABLE_NAME}' AS TABLE_NAME, '{COLUMN_NAME}' AS COLUMN_NAME, COUNT(*) AS ROW_COUNT FROM {TABLE_NAME} WHERE {COLUMN_NAME} LIKE '%{SEARCH}%'

UNION ALL the resulting queries together (add WHERE ROW_COUNT <> 0 to an outer query)

0

精彩评论

暂无评论...
验证码 换一张
取 消