\r\n declare @i int;\r\n
\r\n\r\n select top (@num) s_id from table\r\n
\r\n\r\n 在sqlserver中运行上面语句时报错:\r\n
\r\n\r\n 消息 102,级别 15,状态 1,第 9 行\r\n
\r\n\r\n @num 附近有语法错误。\r\n
\r\n\r\n
\r\n
\r\n SQL2005 中selecdt top后是可以直接跟变量的比如:(但要注意的是变量要用括号括起来)\r\n
\r\n\r\n select top (@i) * from table\r\n
\r\n\r\n 在SQL2000中,Select Top后是不能直接跟变量的:\r\n
\r\n\r\n 要解决2000中top后跟变量的方法有两种:\r\n
\r\n\r\n 第一种: declare @i int,@sql varchar(100)\r\n
\r\n\r\n set @i = 100\r\n
\r\n\r\n set @sql = "select top " + cast(@i as varchar) + " * from table"\r\n
\r\n\r\n exec(@sql)\r\n
\r\n\r\n
\r\n
\r\n 通常我们可以使用这种方法来操作,但有时却不行,比如循环读取记录时(以下这么写会出错)\r\n
\r\n\r\n declare @i int,@sql varchar(100)\r\n
\r\n\r\n set @i = 100\r\n
\r\n\r\n set @sql = "select top " + cast(@i as varchar) + " * from table"\r\n
\r\n\r\n DECLARE rs CURSOR LOCAL SCROLL FOR\r\n
\r\n\r\n --设置数据源\r\n
\r\n\r\n exec(@sql) \r\n
\r\n\r\n OPEN rs\r\n
\r\n\r\n 第二种:使用set rowcount = 100来实现\r\n
\r\n\r\n set rowcount 100 --设置读取的条数\r\n
\r\n\r\n DECLARE rs CURSOR LOCAL SCROLL FOR\r\n
\r\n\r\n --设置数据源\r\n
\r\n\r\n select * from table\r\n
\r\n\r\n OPEN rs\r\n
\r\n\r\n
\r\n
\r\n set rowcount 0 --恢复读取的条数\r\n
\r\n\r\n
\r\n