Here's a solution that, like the @ Decker97 approach, computes from metadata whose columns are text searchable. Assumes 2005+ for using XML PATH, as well as sys.columns, sys.tables, etc. Supports TEXT / NTEXT / CHAR / NCHAR / VARCHAR / NVARCHAR and even puts the leading N in the search bar where necessary. Does not support XML columns. What he does slightly different is that he returns a single set of results for each table, not for each individual column, so you only get one row in each row of the table, even if several columns match. If the goal is to understand how this works and not just have a solution, it will probably take a little more than that ... maybe I should write about this problem (I probably should not be lazy and actually create lists of columns instead of just using SELECT *).
DECLARE @SearchTerm NVARCHAR(32) = 'foo'; DECLARE @TableName NVARCHAR(128) = NULL; SET NOCOUNT ON; DECLARE @s NVARCHAR(MAX) = ''; WITH [tables] AS ( SELECT [object_id] FROM sys.tables AS t WHERE (name = @TableName OR @TableName IS NULL) AND EXISTS ( SELECT 1 FROM sys.columns WHERE [object_id] = t.[object_id] AND system_type_id IN (35,99,167,175,231,239) ) ) SELECT @s = @s + 'SELECT ''' + REPLACE(QUOTENAME(OBJECT_SCHEMA_NAME([object_id])),'''','''''') + '.' + REPLACE(QUOTENAME(OBJECT_NAME([object_id])), '''','''''') + ''',* FROM ' + QUOTENAME(OBJECT_SCHEMA_NAME([object_id])) + '.' + QUOTENAME(OBJECT_NAME([object_id])) + ' WHERE ' + ( SELECT QUOTENAME(name) + ' LIKE ' + CASE WHEN system_type_id IN (99,231,239) THEN 'N' ELSE '' END + '''%' + @SearchTerm + '%'' OR ' FROM sys.columns WHERE [object_id] = [tables].[object_id] AND system_type_id IN (35,99,167,175,231,239) ORDER BY name FOR XML PATH(''), TYPE ).value('.[1]', 'nvarchar(max)') + CHAR(13) + CHAR(10) FROM [tables]; SELECT @s = REPLACE(@s,' OR ' + CHAR(13),';' + CHAR(13)); SELECT @s;
Aaron bertrand
source share