日期:2014-05-19  浏览次数:20391 次

一句闹心的sql 存储过程语句,寻求高手帮忙!
如何把EXEC执行完毕后的ID值给一个变量@startID?
代码如下:
EXEC( 'SELECT   TOP   1   ID   FROM   (
SELECT   TOP   '+@StartCount+ '   ID   FROM   kind
ORDER   BY   ID   ASC
)   a
ORDER   BY   ID   DESC ')
其中@StartCount为入口参数
@startID为存储过程中自己定义的变量。

谢谢!

------解决方案--------------------
请参考:http://topic.csdn.net/t/20030324/17/1570460.html
------解决方案--------------------
sp_executesql
执行可以多次重用或动态生成的 Transact-SQL 语句或批处理。Transact-SQL 语句或批处理可以包含嵌入参数。

语法
sp_executesql [@stmt =] stmt
[
{, [@params =] N '@parameter_name data_type [,...n] ' }
{, [@param1 =] 'value1 ' [,...n] }
]

使用上面这个存储过程,支持参数输出.具体用法去 联机帮助里面看看吧
------解决方案--------------------
declare @StartCount int
set @StartCount=10
declare @startID int
declare @sql Nvarchar(1000)
set @sql= 'SELECT TOP 1 @a=ID FROM (
SELECT TOP '+cast( @StartCount as nvarchar)+ ' ID FROM kind
ORDER BY ID ASC
) a
ORDER BY ID DESC '
exec sp_executesql @sql,N '@a int output ',@startID output
select @startID