日期:2014-05-18  浏览次数:20572 次

SQLServer存储过程的问题
SQL code

@StockCode nvarchar(50),
@days int
as
select min(LowestPrice)
from
(
select top (@days) LowestPrice
from Stocks
where StockCode=@StockCode
order by UpdateTime desc
)t



这是一个在SQLServer 2005 EXPRESS版本里写的存储过程,
可是在远程空间上的数据库里会出错, 好像是2000版本不支持top (@days) 这样的写法,
请问我应该怎样改呢?


------解决方案--------------------
[code=sql]
--用动态sql
xec SP_EXECUTESQL @sql语句
[/code]
------解决方案--------------------
SQL code
 
--用动态sql 
Exec SP_EXECUTESQL @sql语句

------解决方案--------------------
SQL code

declare @sql varchar(8000)

set @sql='select min(LowestPrice)
from
(
select top '+ltrim(@days)+' LowestPrice
from Stocks
where StockCode=@StockCode
order by UpdateTime desc
)t '

exec (@sql)

------解决方案--------------------
SQL code

--两个变量,都需要从外面传进去
declare @sql varchar(8000)

set @sql='select min(LowestPrice)
from
(
select top '+ltrim(@days)+' LowestPrice
from Stocks
where StockCode='+@StockCode+' 
order by UpdateTime desc
)t '

exec (@sql)

------解决方案--------------------
SQL code

declare @sql nvarchar(max)

set @sql='
select min(LowestPrice)
from
(
select top ('+@days+') LowestPrice
from Stocks
where StockCode='''+@StockCode+'''
order by UpdateTime desc
)t'

------解决方案--------------------
SQL code
exec sp_executesql @sql

------解决方案--------------------
SQL code

@StockCode nvarchar(50),
@days int
as
declare @sql varchar(8000)

set @sql='select min(LowestPrice)
from
(
select top '+ltrim(@days)+' LowestPrice
from Stocks
where StockCode='''+@StockCode+''' 
order by UpdateTime desc
)t '

exec (@sql)