How to work around SQL Server's "The maximum number of tables in a query (260) was exceeded."
i have a query that contains a series of 21 UNIONs
, e.g.:
CREATE VIEW dbo.USGovCurrencyOnHandBreakdown AS
SELECT ... FROM a
UNION ALL
SELECT ... FROM b
UNION ALL
SELECT ... FROM c
UNION ALL
SELECT ... FROM d
...
UNION ALL
SELECT ... FROM u
The query runs fine when run alone. But when the query is run through the containing view:
SELECT * FROM USGovCurrencyOnHandBreakdown
Msg 4414, Level 16, State 1, Line 1
Could not allocate ancillary table for view or function resolution. The maximum number of tables in a query (260) was exceeded.
i've tried splitting up my USGovFedExpentiures
view into smaller chunks:
CREATE VIEW开发者_如何学编程 dbo.USGovCurrencyOnHandBreakdown AS
SELECT x FROM TreasuryAuditResults
UNION ALL
SELECT x FROM USGovCurrencyOnHandBreakdown_Additions
UNION ALL
SELECT x FROM USGovCurrencyOnHandBreakdown_Subtractions
With USGovCurrencyOnHandBreakdown_Additions
and USGovCurrencyOnHandBreakdown_Subtractions
each containing roughly half the queries:
CREATE VIEW USGovCurrencyOnHandBreakdown_Additions AS
SELECT ... FROM b
UNION ALL
SELECT ... FROM c
...
SELECT ... FROM k
CREATE VIEW USGovCurrencyOnHandBreakdown_Subtractions AS
SELECT ... FROM l
UNION ALL
SELECT ... FROM m
...
SELECT ... FROM u
But selecting from the "parent" view still fails:
SELECT * FROM USGovCurrencyOnHandBreakdown
Msg 4414, Level 16, State 1, Line 1
Could not allocate ancillary table for view or function resolution. The maximum number of tables in a query (260) was exceeded.
How can i work around the 256 table limit?
See also
- FIX: A Transact-SQL query that uses views may fail unexpectedly in SQL Server 2000 SP3
- MSDN: Maximum Capacity Specifications for SQL Server
A colleague came up with a great answer. Use a function to return a table variable; insert the results into the table variable bit by bit:
CREATE VIEW dbo.USGovCurrencyOnHandBreakdown AS
SELECT * FROM fn_USGovCurrencyOnHandBreakdown()
with the view now calling the UDF:
CREATE FUNCTION dbo.fn_USGovCurrencyOnHandBreakdown()
RETURNS @Results TABLE
(
Total money,
...
)
INSERT INTO @Results SELECT ... FROM a
INSERT INTO @Results SELECT ... FROM b
INSERT INTO @Results SELECT ... FROM c
INSERT INTO @Results SELECT ... FROM d
...
INSERT INTO @Results SELECT ... FROM u
RETURN
END
As far as any clients know the view
is unchanged. (Except now it works!)
You could store the subqueries into temp tables, e.g. the USGovCurrencyOnHandBreakdown_Additions
and USGovCurrencyOnHandBreakdown_Subtractions
that you mentioned, and than selecting from those temp tables instead of views.
Of course, the transactions could be an issue because of the dirty reads, I don't know if that's a concern in this case...
精彩评论