select 中如何使用变量。

whoo 2003-04-02 03:41:56
源语句:select top 10 from table;

改进,
写成存储过程

create procedure dbo.FetchFirstNumRows
@Num int as

select top @Num from table;


这么些是肯定不行的,问题是无论如何该也不行。好像select语句中不能使用变量。

那位有简单的解决办法?

10分钟后我再来。
...全文
137 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
whoo 2003-04-02
  • 打赏
  • 举报
回复
sorry, 各位。

exec后面要加括号才行。 不好意思,帖子都结了。
whoo 2003-04-02
  • 打赏
  • 举报
回复
理论上各位的方法都是可行的,可实际运行就是报错。

所有使用cast的都不行,很奇怪的是即使打印出来的语句是正确也不行。
只有 zxm954712(三绝剑)的 方法可以正常运行。

无非就是用的convert, 会有这种区别么?
实际上 即使是这么直接写: exec 'select * from table';都不能执行。

那位知道原因的话,另行开贴结分。
vbasten 2003-04-02
  • 打赏
  • 举报
回复
create procedure dbo.FetchFirstNumRows
@Num int as

exec ('select top '+cast(@Num as varchar)+' from table;')
wenhao676 2003-04-02
  • 打赏
  • 举报
回复
CREATE PROCEDURE test
@key_String varchar(200)

AS
declare @strSQL nvarchar (3000)
select @key_string=replace(@key_string,'''','''''')
select @strSQL = 'SELECT * FROM Product '
select @strSQL = @strSQL + 'WHERE (Prod_name like ''%' +@key_String + '%'' or Model like ''%' + @key_String + '%'''

................
exec sp_executesql @strSQL






GO
wgy2008 2003-04-02
  • 打赏
  • 举报
回复
ALTER PROCEDURE SP_WGY @BH INT
AS
EXEC('SELECT TOP '+CAST(@BH AS VARCHAR)+' * FROM AAA')

shengyh 2003-04-02
  • 打赏
  • 举报
回复
同上,我要接分1!!!!!
shengyh 2003-04-02
  • 打赏
  • 举报
回复
谁说存储过程中不能使用变量!!!在存储过程中定义declare @num int就可以使用这个变量了!!!
yoki 2003-04-02
  • 打赏
  • 举报
回复
create procedure dbo.FetchFirstNumRows
@Num int as

exec ('select top '+cast(@Num as VARCHAR)+' from table')
pengdali 2003-04-02
  • 打赏
  • 举报
回复
create procedure dbo.FetchFirstNumRows
@Num int as

exec ('select top '+cast(@Num as varchar)+' from table;')
zxm954712 2003-04-02
  • 打赏
  • 举报
回复

drop proc test
GO
create proc test
@num int
as
declare @strSql varchar(1000)
select @strSql = 'select top '+ convert(varchar, @num) + ' * from employees'
print @strSql
exec(@strSql)
GO
test 10


try it:)
愉快的登山者 2003-04-02
  • 打赏
  • 举报
回复
create procedure dbo.FetchFirstNumRows
@Num int as

exec ('select top '+cast(@Num as char)+' from table;')

whoo 2003-04-02
  • 打赏
  • 举报
回复
exec szSQL; error:找不到存储过程szSQL;
exec @szSQL: error: 找不到存储过程‘selct top 3 from talbe';

exec('select top 10 * from table'); error:from附近有错误


大家用的是sql server么? 怎么在我这儿就不行了。
teaism 2003-04-02
  • 打赏
  • 举报
回复
create procedure dbo.FetchFirstNumRows
@Num int as

exec('select top '+rtrim(@Num)+' from table;')
hilite2000 2003-04-02
  • 打赏
  • 举报
回复
declare @szSQL as varchar(200)

set @szSQL='select top ' + @Num + ' * from table'

exec szSQL

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧