Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi all,

 

I'm writing a very simple SQL script that performs a simple "select" query. The thing is that I want to use a "top" selection (select top 20 * from MyTable), however I want to use a parameter instead of a fixed number (select top X * from MyTable)

I tried this:

 

declare @MyTop as int

set @MyTop=20

select top @MyTop * from MyTable

 

Well...it doesn't work.

I'm getting a "Incorrect syntax near '@MyTop'." message.

Any idea how I should do this?

 

Thanks.

P.s. - I'm working with MSSQL.

  • Administrators
Posted

the top clause doesn't support variables - then again it isn't ANSI standard anyway ;(

 

you will need to set the rowcount variable to limit the maximum number of rows...

 


declare @rows int
set @rows = 10

SET ROWCOUNT @rows

select * from customers

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

  • Moderators
Posted

Actualy it can be done....

 

You can even soft-code the table or column names if needed.

declare @MyTop as int
set @MyTop=20
declare @Sql varchar(1000)
DECLARE @Crlf	NCHAR(2)
SET @Crlf = CHAR(13) + CHAR(10)

set @Sql = 	'BEGIN  TRANSACTION' + @Crlf +
	'select top ' + @MyTop +  ' * from MyTable' + @Crlf +
	'COMMIT TRANSACTION' + @Crlf 	

Begin transaction
exec (@Sql)
commit transaction

Visit...Bassic Software

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...