我只有35个表但是当我运行下面列出的查询时出现此错误。查询处理器耗尽了内部资源,无法生成查询计划。这是一种罕见的事件,仅适用于引用大量表或分区的极其复杂的查询或查询。请简化查询。如果您认为错误地收到了此消息,请与客户支持服务联系以获取更多信息。我怎么能怀疑查询以避免这个错误?
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
答案 0 :(得分:1)
目前尚不清楚这个查询的目标是什么,但UNION的内容非常昂贵。您需要重写查询。
也许您可以使用BEGIN / END来逐行填充表格。