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!

using TOP in dynamic SQL 2

Status
Not open for further replies.

CompCodeBoy

Programmer
Aug 18, 2005
33
US
Declare @number int
set @number=10
DECLARE @strSQL varchar(1200)

set @strSQL = ' select top ('+ @number + ') account from contact'

EXEC(@strSQL)

The error I get is :
Conversion failed when converting the varchar value ' select top (' to data type int.

Any help would be appreciated
 
Code:
Declare @number int
set @number=10
DECLARE @strSQL varchar(1200)

set @strSQL = ' select top (' + [!]Convert(VarChar(20), [/!]@number[!])[/!] + ') account from contact'

EXEC(@strSQL)

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
try this:

set @strSQL = ' select top '+ convert(varchar,@number) + ' account from contact'


< M!ke >
"Believe, but verify.
 
Dang! I'm getting slow in my old age! ;-)

< M!ke >
"Believe, but verify.
 
I should win, George, 'cause I took out the parens (two less keystrokes!). :p

< M!ke >
"Believe, but verify.
 
I think you can avoid dynamic SQL in this scenario.

Code:
Declare @number int
set @number = 10
SET ROWCOUNT  @number
select account from contact

Also if you are using SQL 2005 you can use TOP with variables

Code:
Declare @number int
set @number = 10
select TOP (@number) account from contact

Sunil
 
And with the ROWCOUNT, specify SET ROWCOUNT 0 to set this option off so that all rows are returned again.

< M!ke >
"Believe, but verify.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top