How to work around SQL Server's “The maximum number of tables in a query (260) was exceeded.”

后端 未结 2 1325
梦如初夏
梦如初夏 2021-01-22 06:44

i have a query that contains a series of 21 UNIONs, e.g.:

CREATE VIEW dbo.USGovCurrencyOnHandBreakdown AS

   SELECT ... FROM a
   UNION ALL
   SELE         


        
相关标签:
2条回答
  • 2021-01-22 06:57

    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...

    0 讨论(0)
  • 2021-01-22 07:09

    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!)

    0 讨论(0)
提交回复
热议问题