TOP And UNIONs

Kevin Feasel

2017-11-27

T-SQL

Andy Levy points out that the TOP operator doesn’t always apply to each element in a UNION:

This system uses TOP every now and then trying to limit the number of records it gets back (and the developers always seem to use the arbitrary 301 – I’m guessing some degree of cargo cult programming going on). I’d prefer a well-constructed WHERE clause to limit the result set but beggars can’t be choosers when working with legacy vendor code.

What I found odd was that the Ledger1 table didn’t get a lot of traffic – with the WHEREclause in use (omitted here for brevity), you’d only get a handful of records, maybe a dozen at most.

Click through to see the rest of the problem, as well as Andy’s solution.

Related Posts

Identity Inserts: One Table at a Time

Bert Wagner shows that you can only insert with IDENTITY_INSERT = ON for one table at a time: Ok, simple enough to fix: we just need to do what the error message says and SET IDENTITY_INSERT ON for both tables: SET IDENTITY_INSERT dbo.User_DEV ON; SET IDENTITY_INSERT dbo.StupidQuestions_DEV ON; And… it still didn’t work: IDENTITY_INSERT is […]

Read More

Using APPLY to Reduce Function Calls

Erik Darling shows a clever use of the APPLY operator: A while back, Jonathan Kehayias blogged about a way to speed up UDFs that might see NULL input. Which is great, if your functions see NULL inputs. But what if… What if they don’t? And what if they’re in your WHERE clause? And what if they’re in […]

Read More

Categories

November 2017
MTWTFSS
« Oct Dec »
 12345
6789101112
13141516171819
20212223242526
27282930