sqlserver 存储过程中的top+变量使用分析(downmoon)

前端之家收集整理的这篇文章主要介绍了sqlserver 存储过程中的top+变量使用分析(downmoon)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

存储过程中的TOP后跟一个变量会如何?
<div class="codetitle"><a style="CURSOR: pointer" data="34414" class="copybut" id="copybut34414" onclick="doCopy('code34414')"> 代码如下:

<div class="codebody" id="code34414">
Create proc getWorkPlan2
(@intCounter int
,@lngUserID int)
as
select Top 5 lngWorkID,strWorkName,strExecHumanName,strBeginDate
from worklist where lngExecHumanID= @lngUserID
order by lngWorkID desc

现在想将这里的Top 5 改为变量· Top @intCounter
如下
<div class="codetitle"><a style="CURSOR: pointer" data="26128" class="copybut" id="copybut26128" onclick="doCopy('code26128')"> 代码如下:
<div class="codebody" id="code26128">
ALTER proc getWorkPlan2
(@intCounter int
,@lngUserID int)
as  
)
exec sp_executesql ('select Top '+convert(varchar(10),@intCounter)+' lngWorkID,strBeginDate from worklist where lngExecHumanID= '
+convert(varchar(10),@lngUserID) +' order by lngWorkID desc '

老是提示 在关键字 'convert' 附近有语法错误
OK!
于是改为
<div class="codetitle"><a style="CURSOR: pointer" data="4102" class="copybut" id="copybut4102" onclick="doCopy('code4102')"> 代码如下:
<div class="codebody" id="code4102">
ALTER proc getWorkPlan2
(@intCounter int
,@lngUserID int)
as
declare @strCounter varchar(10)
set @strCounter=convert(varchar(10),@intCounter)
declare @strUserID varchar(10)
set @strUserID=convert(varchar(10),@lngUserID)
exec sp_executesql ('select Top '+@strCounter+' lngWorkID,strBeginDate from worklist where lngExecHumanID= '
+@strUserID +' order by lngWorkID desc '
)

后来,经saucer(思归)大哥提醒,发现可以用以下语句实现(sql2005/2008):
<div class="codetitle"><a style="CURSOR: pointer" data="43622" class="copybut" id="copybut43622" onclick="doCopy('code43622')"> 代码如下:
<div class="codebody" id="code43622">
Alter proc getWorkPlan2
(
@intCounter int
,@lngUserID int
)
as
set rowcount @intCounter
select lngWorkID,strBeginDate
from worklist where lngExecHumanID= @lngUserID
order by lngWorkID desc

邀月注:本文版权由邀月和博客园共同所有,转载请注明出处。

top存储过程

猜你在找的MsSQL相关文章