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

求助解决存储过程:top参数和字符串共存问题
问题是这样的:
1,创建一个存储过程
CREATE PROCEDURE Location
(
@Topcount int,
@Location char(50) 
)
as
declare @strCounter varchar(10)
set @strCounter=convert(varchar(10),@Topcount) 
exec('select top '+@strCounter+' * from tt where [_FontOrImage]=1 and [Location]='+@Location+' Order By _Start_Time Desc')
GO
2,tt库表里的Location字段为char(50)
结果在查询分析器里查询时出现以下问题:
exec Location 1,'1k'

服务器: 消息 170,级别 15,状态 1,行 1
第 1 行: 'k' 附近有语法错误。

但是,当执行exec Location 1,'1'时可以查询出数据.

而'1k'和'1'字符串在Location字段都存在,为什么出现这样的问题啊?求求各位了!

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


--存储过程名不要和变量一样
CREATE   PROCEDURE   [dbo].[sproLocation] 
( 
@Topcount   int, 
@Location   char(50)   
) 
as 
declare   @strCounter   varchar(10) 
set   @strCounter=convert(varchar(10),@Topcount)   
exec('select top '+'('+@strCounter+')'+' *  from tt where [_FontOrImage]=1 and  [Location]='+@Location+'Order By _Start_Time Desc') 
GO

------解决方案--------------------
SQL code
--字符串前后要加引号,
exec('select   top   '+@strCounter+'     *   from   tt   where   [_FontOrImage]=1   and   [Location]='+@Location+'   Order   By   _Start_Time   Desc') 
--->
exec('select   top   '+@strCounter+'     *   from   tt   where   [_FontOrImage]=1   and   [Location]='''+@Location+'''   Order   By   _Start_Time   Desc')

------解决方案--------------------
SQL code
CREATE   PROCEDURE   Location 
( 
@Topcount   int, 
@Location   char(50)   
) 
as 
declare   @strCounter   varchar(10) 
set   @strCounter=convert(varchar(10),@Topcount)   
exec('select   top   '+@strCounter+'     *   from   tt   where   [_FontOrImage]=1   and   [Location]='''+@Location+'''   Order   By   _Start_Time   Desc') 
GO