all groups > sql server programming > february 2007 >
You're in the

sql server programming

group:

select top (select count(*)/4 from tbl1) * from tbl1 - how to do t


select top (select count(*)/4 from tbl1) * from tbl1 - how to do t Rich
2/17/2007 8:06:05 PM
sql server programming:
Greetings,

I need to select a quarter of the rows from a table. I tried this syntax
with no luck

select top (select count(*)/4 from temp1b) * from temp1b

my alternative is to do this:

Declare @i int
Select @i = Count(*)/4 From tbl1
Select top @i * from tbl1

What is the correct synatxt to do is using this version?
select top (select count(*)/4 from temp1b) * from temp1b

Thanks,
Re: select top (select count(*)/4 from tbl1) * from tbl1 - how to do t Kalen Delaney
2/17/2007 8:24:12 PM
What version are you using? What does 'no luck' mean? Did you get an error
message? What did it say?

SQL Server 2005 lets you use an expression with TOP, but the expression,
even if just a variable, must be in parenthesis.

SELECT TOP(@i) * FROM temp1b

However, you might also consider trying a simple percentage, which is
available in SQL 2000:

SELECT TOP 25 PERCENT FROM temp1b
--
HTH
Kalen Delaney, SQL Server MVP
http://sqlblog.com


[quoted text, click to view]

RE: select top (select count(*)/4 from tbl1) * from tbl1 - how to do t Rich
2/17/2007 8:28:07 PM
Oh, and I already know that I could do this:

Select top 25 percent * from tbl1

But the exercise is to find syntax like this:

select top (select count(*)/4 from temp1b) * from temp1b

just to see it if is doable - for other purposes.


[quoted text, click to view]
Re: select top (select count(*)/4 from tbl1) * from tbl1 - how to Rich
2/17/2007 9:28:05 PM
Thank you for your reply. I am using Sql Server 2000

I realize thatt I could do this:

Select top 25 percent * from tbl1

But the exercise is to find syntax to do something like this:

select top (select count(*)/4 from temp1b) * from temp1b

When I tried this I got 2 error messages that just said
syntax error near "(" and syntax error near *

just to see it if is doable - for other purposes.

The idea is to not have to include these lines
Declare @i int
Select @i = Count(*)/4 from tbl1

Is something like what I am trying to do feasable?

[quoted text, click to view]
Re: select top (select count(*)/4 from tbl1) * from tbl1 - how to Tibor Karaszi
2/18/2007 12:00:00 AM
[quoted text, click to view]

2000 only accept a constant for the value of TOP. You would have to use dynamic SQL or SET ROWCOUNT
for anything else. 2005 accepts a variable or a scalar subquery.

--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi


[quoted text, click to view]
AddThis Social Bookmark Button