当前位置: 代码迷 >> Sql Server >> select top 后面不能跟变量吗?解决办法
  详细解决方案

select top 后面不能跟变量吗?解决办法

热度:50   发布时间:2016-04-27 21:01:08.0
select top 后面不能跟变量吗?
需求:
实现一个简单的分页存储过程。不使用通用存储过程,不到万不得已不使用存储过程内的字符串拼接。
实现:
set   ANSI_NULLS   ON
set   QUOTED_IDENTIFIER   ON
go

CREATE   PROCEDURE   [dbo].[sp_QueryPage_User]
@Page   int   =   1,
@PageSize   int   =   10
AS
BEGIN

--   SET   NOCOUNT   ON   added   to   prevent   extra   result   sets   from
--   interfering   with   SELECT   statements.
SET   NOCOUNT   ON;

select   top   @PageSize   *   from   tbl_User  
where   (UserNativeId   not   in   (select   top   @[email protected]   UserNativeId   from   tbl_User   order   by   UserNativeId))
order   by   UserNativeId
END
go

错误提示:
Msg   102,   Level   15,   State   1,   Procedure   sp_QueryPage_User,   Line   15
Incorrect   syntax   near   '@PageSize '.
Msg   102,   Level   15,   State   1,   Procedure   sp_QueryPage_User,   Line   16
Incorrect   syntax   near   '@Page '.

分析:   将变量替换为常量后可以通过
            例如将
select   top   @PageSize   *   from   tbl_User  
where   (UserNativeId   not   in   (select   top   @[email protected]   UserNativeId   from   tbl_User   order   by   UserNativeId))
order   by   UserNativeId
替换为
select   top   10   *   from   tbl_User  
where   (UserNativeId   not   in   (select   top   30   UserNativeId   from   tbl_User   order   by   UserNativeId))
order   by   UserNativeId

求解:   select   top   后面不能跟变量?还是有什么别的语法可以通过的?


------解决方案--------------------
declare @int int
set @int =1
exec( 'select top '[email protected]+ ' form sysobjects ')
------解决方案--------------------
CREATE PROCEDURE [dbo].[sp_QueryPage_User]
@Page int = 1,
@PageSize int = 10
AS
declare @sql varchar(1000)
BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
set @sql= '
select top '[email protected]+ ' * from tbl_User
where (UserNativeId not in (select top '[email protected][email protected]+ ' UserNativeId from tbl_User order by UserNativeId))
order by UserNativeId '
exec(@sql)
END
go
------解决方案--------------------
declare @num int
select @num = 10
exec( 'select top '[email protected]+ ' * from sysobjects ')
------解决方案--------------------
用动态SQL语句。


动态sql语句基本语法
1 :普通SQL语句可以用Exec执行

eg: Select * from tableName
Exec( 'select * from tableName ')
Exec sp_executesql N 'select * from tableName ' -- 请注意字符串前一定要加N

2:字段名,表名,数据库名之类作为变量时,必须用动态SQL

eg:
declare @fname varchar(20)
set @fname = 'FiledName '
Select @fname from tableName -- 错误,不会提示错误,但结果为固定值FiledName,并非所要。
Exec( 'select ' + @fname + ' from tableName ') -- 请注意 加号前后的 单引号的边上加空格
  相关解决方案