Click here to Skip to main content
14,367,789 members

Get Top X rows from a table

Rate this:
5.00 (7 votes)
Please Sign up or sign in to vote.
5.00 (7 votes)
23 Feb 2012CPOL
How to use variable in SELECT TOP SQL command
Sometimes, we do very ugly things just because of missing simple tricks.

I believe all of the devs who work with SQL use SELECT TOP command as they need. This is a very simple SQL command.


Now, sometimes you need to use variable instead of constant number (say 10). If you write the query as:

DECLARE @count int
SET @count = 20

This will give you a syntax error.

To solve this issue, we sometimes write dynamic SQL (SQL statements constructed inside a string variable) and execute that.

But we all know dynamic SQL is always bad for many reasons and we should avoid that as far as we can.

We can avoid dynamic SQL in this scenario very easily with a simple trick. Once you know that, you will laugh at yourself if you really used dynamic SQL for this scenario.

The Solution:

DECLARE @count int
SET @count = 20

Did you mark the trick? Yes, you just need enclose the variable with a Bracket ().

By the way, this trick is Microsoft SQL Server specific. Experts from Oracle or mysql may post alternatives from those platforms.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mahmud Hasan
Software Developer (Senior)
Netherlands Netherlands
Software Engineer | Software Architect | System Designer | System Analyst | Team Leader | Consultant (.Net)

12 Years of Experience in the Industry.

Currently working as System Designer at CIMSOLUTIONS, Netherlands

View My Profile in LinkedIn

Comments and Discussions

GeneralReason for my vote of 5 nice one Pin
Nikhil_S22-Feb-12 1:54
professionalNikhil_S22-Feb-12 1:54 
GeneralRe: Thanks. Pin
Mahmud Hasan22-Feb-12 5:50
memberMahmud Hasan22-Feb-12 5:50 
GeneralReason for my vote of 5 Thanks! Pin
Pablo Aliskevicius21-Feb-12 22:33
memberPablo Aliskevicius21-Feb-12 22:33 
GeneralRe: Thanks. Pin
Mahmud Hasan21-Feb-12 22:36
memberMahmud Hasan21-Feb-12 22:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 20 Feb 2012


4 bookmarked