简体   繁体   中英

SQL Server: What's the limit on number of UNIONs?

I was wondering if there's a limit on a number of UNION'ed SELECT statements I can send to an SQL Server? I may have up to 36 done in one SQL statement, so it becomes quite long, character wise. (Also each of those SELECT statements is a somewhat complex by itself with CASE WHEN statements in it.)

From SQL 2008 BOL

"Any number of UNION operators can appear in a Transact-SQL statement"

Also from MSDN "Maximum Capacity Specifications for SQL Server" (2008):

Batch size (1) 65,536 * Network Packet Size

Length of a string containing SQL statements (batch size) (1) 65,536 * Network packet size

(1) Network Packet Size is the size of the tabular data stream (TDS) packets used to communicate between applications and the relational Database Engine. The default packet size is 4 KB, and is controlled by the network packet size configuration option.

To my mind, that means 268,435,456 bytes when using defaults. Please say your query is shorter than that.

Necromancing, because I now know the real-life answer.

Technically, like Neil Moss said, > 268 million bytes (ASCII characters), or > 134 million UTF-16 characters.

However, there is a limit of " 256 tables per SELECT statement ".

And while you can use more than 256 tables in a query WITH UNION STATEMENTS , such a query cannot be used as a view, table-valued function or as a subquery for a SELECT statement.

Also, if you use such a query directly, you may hit the stack space limit of the query optimizer at around 1'300-1'500 SELECTs.

I know, because thanks to a great (warning - sarcasm) OCP (original code "programmer"), we have such af*ed up schema, and I actually ran into both, the 256 and the 1'300-1'500 limit.

(one table per object type, in case anybody wonders; with exactly the same column-schema (but not names) per table - instead of a reference table with object-type...)

According to this post somwhere between 8000 and 16000, for his particular query. Is probably mostly goverened by the resources available to your SQL Server.

It might be worth asking another question about the particular case you have for an alternative method that doesn't need so many unions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM