Reputation: 351
I only have 35 tables but when I run the query listed below I get this error. The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information. How could I wright the query to avoid this error?
CREATE TABLE DemoTable
(
ID INT identity(1,1),
col nvarchar(20)
)
*/
/*INSERT INTO DemoTable VALUES
('P000092436'),
('123466'),
('123456'),
('P000092436'),
('13456'),
('P000092436')*/
DECLARE @SearchStr nvarchar(100) = '92436',
@SQL nvarchar(max) = ''
/*SELECT @SQL = @SQL +
'UNION
SELECT '''+ QUOTENAME(t.TABLE_SCHEMA) +'.'+ QUOTENAME(c.TABLE_NAME) +'.'+QUOTENAME(c.COLUMN_NAME) +''' As ColumnName,
'''+ @SearchStr +''' As ColumnValue,
(SELECT * FROM '+ QUOTENAME(c.TABLE_NAME) +' WHERE '+ QUOTENAME(c.COLUMN_NAME) +' LIKE ''%'+ @SearchStr +'%'' FOR XML AUTO)
FROM '+ QUOTENAME(c.TABLE_NAME) +'
WHERE '+ QUOTENAME(c.COLUMN_NAME) +' LIKE ''%'+ @SearchStr +'%''*/
SELECT @SQL = @SQL +
'UNION
SELECT '''+ t.TABLE_SCHEMA +'.'+ c.TABLE_NAME +'.'+c.COLUMN_NAME +''' As ColumnName,
'''+ @SearchStr +''' As ColumnValue, ' + '''<'' + ' + 'CAST(' + '
(SELECT ' + n.LIST_COLUMN + 'FROM '+ c.TABLE_NAME +' WHERE '+ c.COLUMN_NAME +' LIKE ''%'+ @SearchStr +'%'' FOR XML PATH(''''), TYPE) AS VARCHAR(MAX)) + ''/>''
FROM '+ c.TABLE_NAME +'
WHERE '+ c.COLUMN_NAME +' LIKE ''%'+ @SearchStr +'%''
'
--SELECT c.COLUMN_NAME, t.TABLE_NAME, n.LIST_COLUMN
FROM INFORMATION_SCHEMA.COLUMNS c
INNER JOIN INFORMATION_SCHEMA.TABLES t ON c.TABLE_NAME = t.TABLE_NAME
INNER JOIN
(
select
b.TABLE_NAME,
stuff((select ',''"'' + CAST('+ a.COLUMN_NAME + ' AS VARCHAR(200)) + ''",'''
from INFORMATION_SCHEMA.COLUMNS a
where a.TABLE_NAME = b.TABLE_NAME
For XML PATH('')),1,1,'') LIST_COLUMN
from (select distinct TABLE_NAME from INFORMATION_SCHEMA.COLUMNS) b
) n ON n.TABLE_NAME = c.TABLE_NAME
WHERE t.TABLE_TYPE = 'BASE TABLE';
SET @SQL = STUFF(@SQL, 1, 7, '')
IF OBJECT_ID('tempdb..#SearchResults') IS NOT NULL
/*Then it exists*/
DROP TABLE #SearchResults
CREATE TABLE #SearchResults
(
ColumnName nvarchar(500),
ColumnValue nvarchar(100),
--RowContent XML
RowContent nvarchar(max)
)
PRINT @SQL;
INSERT INTO #SearchResults
EXEC(@SQL)
SELECT *
FROM #SearchResults
Upvotes: 0
Views: 104
Reputation: 113
It is not clear what your goal is with this query, but the UNION stament is very expensive. You need to rewrite the query.
Maybe you can make use of BEGIN/END to populate your table evaluating row by row.
Upvotes: 1