views:

176

answers:

2

Hello All,

I couldn't solve that mistery question in SQL SERVER.

Here an example that I tried to do and it didn't work.

DECLARE @Total int;
SET @Total = (SELECT COUNT(*)-10 FROM MYTABLE)

SELECT TOP @Total IdColumn FROM MYTABLE

How can I use the following query

SELECT COUNT(*)-10 FROM MYTABLE

as an integer variable, somewhere else in my code.

+4  A: 

When you use a variable in a top clause, you need to use parenthesis, like this:

SELECT TOP (@Total) IdColumn FROM MYTABLE

If you are using SQL2000, you cannot use a variable in a top clause. If you try, you will get a parse/syntax error. Instead, you can use RowCount, like this:

DECLARE @Total int;
SET @Total = (SELECT COUNT(*)-10 FROM MYTABLE)

Set RowCount @Total
SELECT IdColumn FROM MYTABLE
Set RowCount 0
G Mastros
Just tested and it works... no freaking way... I've missed this all this time... /me fails. +1 :D
md5sum
Gives that error for me Line 4: Incorrect syntax near '('.
stckvrflw
I just updated my answer to include SQL2000 functionality. You should probably have mentioned the version of SQL Server you are using in your original question.
G Mastros
Yep, I also edited my question.
stckvrflw
+1  A: 

Use Brackets: The following works for me:

DECLARE @Total int;
SET @Total = (SELECT COUNT(*)-10 FROM MYTABLE)

SELECT TOP (@Total) IdColumn FROM MYTABLE
zoidbeck
Line 4: Incorrect syntax near '(' Exactly the same things I wrote.
stckvrflw
Yes you are right: This only works for SQLServer 2003 and up.
zoidbeck