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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to convert this value into a stored procedure variable? 1

Status
Not open for further replies.

childrenfirst

Technical User
Oct 15, 2006
80
US
Hi,

I have a query and it works, but I am trying to pass a variable to the query and failed at this point.

Original query (and worked!):

SELECT Top 5 counter
FROM Employee
ORDER BY NewID()

Try To (and did not work...):

DECLARE @selectnumber AS int

SELECT Top @selectnumber counter
FROM Employee
ORDER BY NewID()


Any advice will be greatly appreciated!!
 
You would have to do it as Dynamic SQL such as:

DECLARE @sql AS varchar
DECLARE @selectnumber AS int

SET @sql = 'SELECT Top ' + CAST(@selectnumber AS varchar) + ' counter FROM Employee ORDER BY NewID()'

EXEC (@sql)

 
DECLARE @selectnumber AS int
set @selectnumber = 5
set rowcount @selectnumber
SELECT counter
FROM Employee
ORDER BY NewID()
set rowcount 0
 
use set rowcount

Code:
DECLARE @selectnumber AS int
set @selectnumber = 5

set rowcount @selectnumber

SELECT  counter
FROM Employee
ORDER BY NewID()

set rowcount 0

Denis The SQL Menace
SQL blog:
 
You don't need dynamic SQL to do this.

Code:
DECLARE @selectnumber AS int
Set @SelectNumber = [!]8[/!] [green] -- As An Example[/green]

[!]Set RowCount @selectnumber[/!]

SELECT counter
FROM Employee
ORDER BY NewID()

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
I'm not feeling well, so I'm going back to bed. [sad]

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Hi All,

Thank you so much for brainstorming for me. In the stored procedure I am working on, a dynamic SQL will work better:) Thank you all! Happy holiday:D


 
Hi,

Glad I could help. Thanks for the star!

Regards,
Tom

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top