top+ Variable usage analysis (downmoon) in SQL Server stored procedures _mssql2005

Source: Internet
Author: User
What happens when top in a stored procedure is followed by a variable?
Copy Code code as follows:

Create proc GetWorkPlan2
(@intCounter int
, @lngUserID int)
As
Select Top 5 lngworkid,strworkname,strexechumanname,strbegindate
From worklist where lngexechumanid= @lngUserID
ORDER BY Lngworkid Desc

Now I want to change the top 5 here to variable · Top @intCounter
As follows
Copy Code code as follows:

ALTER proc GetWorkPlan2
(@intCounter int
, @lngUserID int)
As
)
EXEC sp_executesql (' Select top ' +convert (varchar), @intCounter) + ' Lngworkid,strworkname,strexechumanname, Strbegindate from worklist where lngexechumanid= '
+convert (varchar, @lngUserID) + ' ORDER by lngworkid Desc '

Always prompt for syntax errors near the keyword ' convert '.
Ok!
So instead
Copy Code code as follows:

ALTER proc GetWorkPlan2
(@intCounter int
, @lngUserID int)
As
DECLARE @strCounter varchar (10)
Set @strCounter =convert (varchar), @intCounter)
DECLARE @strUserID varchar (10)
Set @strUserID =convert (varchar), @lngUserID)
EXEC sp_executesql (' select top ' + @strCounter + ' lngworkid,strworkname,strexechumanname,strbegindate from worklist where Lngexechumanid= '
+ @strUserID + ' ORDER by lngworkid Desc '
)

Later, after Saucer (Shi) eldest brother reminded, found that you can use the following statement to achieve (sql2005/2008):
Copy Code code as follows:

Alter proc GetWorkPlan2
(
@intCounter int
, @lngUserID int
)
As
SET ROWCOUNT @intCounter
Select Lngworkid,strworkname,strexechumanname,strbegindate
From worklist where lngexechumanid= @lngUserID
ORDER BY Lngworkid Desc

Invite the Month Note: This article copyright by invite month and the blog Garden Common All, reprint please indicate the source.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.