Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SELECT TOP <variable> FROM ...

Status
Not open for further replies.

smn198

Technical User
Oct 29, 2004
24
0
0
GB
I am trying to get around SQL's inability to use TOP with a variable. I am trying to select the TOP X and order by NEWID() to get X random records in a table. Any ideas?!
 
What kind of Database? TOP is supported in sql server, but not in Oracle..You can get around it in oracle by using ROWNUM...ie

Code:
SELECT Col1, Col2
FROM TABLE
WHERE ROWNUM < 100;

Use your resources, you're on the internet!
 
Dymanic SQL is going to be your answer.
Code:
declare @top int
declare @CMD varchar(1000)
set @Top = 5
set @CMD = 'select top ' + @Top + ' * from {table}'
exec @CMD

Denny

--Anything is possible. All it takes is a little research. (Me)

[noevil]
(My very old site)
 
Thanks for the replies. I neglected to mention the SQL is actually going into an application. All I can write are static queries and not Dynamic SQL as what I write is a string to be used as a subquery.
 
I'd recommend converting the entire query into a stored proc. If that isn't an option your pretty much out of luck, unless you can have the app generate the query for you.

Denny

--Anything is possible. All it takes is a little research. (Me)

[noevil]
(My very old site)
 
As in ?
Variable = "SELECT TOP " & MY_COP & " FROM ....."
Eitehr way convert to stored proc ! It's going to be for the best :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top