Paul Maddox

Software development team leader specialising in Microsoft Visual C# and C++ from the Northwest of England. Experience working in a globalised business and team; understanding of enterprise business operation and practices; experience reporting to executive management Skills in numerous languages and technologies; knowledge of formal software development lifecycle; experience of architecture design

Sunday, March 21, 2010

T-SQL Parameterized SELECT TOP @N

If you wanted to select the TOP N rows from a table based on a stored procedure parameter you would likely have tried:

SELECT TOP @N * FROM MyTable

Having come across the error:

Incorrect syntax near '@N'

You would next have hit google and, like me, found a lot of FUD surrounding performing what you would think would be a relatively simple operation.  You would have found talk about dynamic SQL, and no doubt all kinds of other hacks to get around it.  However, from SQL 2005, you can do this:

SELECT TOP (@N) * FROM MyTable

It's as simple as that.  Another good example where the highest ranked result isn't necessarily the right one.