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

请教,简单的查询存储过程语法检查成功,但是运行出错
CREATE   proc   search_info
@searchnum   varchar(20),
@searchtable   varchar(20),
@searchtype   varchar(20),
@searchdata   varchar(20),
@searchid   varchar(20)
as
declare   @sql   varchar(100)
set   set   @sql   =   '   select   top   '   +   @searchnum   +   '   *   from   '   +   @searchtable   +   '   where   '   +   @searchtype   + '   like     %   '   +   @searchdata   +   '   %       order   by   '   +   @searchid+   '   desc '
EXEC(@sql)
GO

exec   search_info   '10 ', 'news ', 'strsubject ', '景湖 ', 'id '
服务器:   消息   170,级别   15,状态   1,行   1
第   1   行:   '景湖 '   附近有语法错误。


------解决方案--------------------
CREATE proc search_info
@searchnum varchar(20),
@searchtable varchar(20),
@searchtype varchar(20),
@searchdata varchar(20),
@searchid varchar(20)
as
declare @sql varchar(100)
set set @sql = ' select top ' + @searchnum + ' * from ' + @searchtable + ' where ' + @searchtype + ' like ' '% ' + @searchdata + ' % ' ' order by ' + @searchid+ ' desc '
EXEC(@sql)
GO
------解决方案--------------------

alter proc search_info
@searchnum varchar(20),
@searchtable varchar(20),
@searchtype varchar(20),
@searchdata varchar(20),
@searchid varchar(20)
as
declare @sql varchar(100)
set set @sql = ' select top ' + @searchnum + ' * from ' + @searchtable + ' where ' + @searchtype + ' like ' '% ' + @searchdata + ' % ' ' order by ' + @searchid+ ' desc ' ---这句改一下
EXEC(@sql)
GO
------解决方案--------------------
set set @sql = ' select top ' + @searchnum + ' * from ' + @searchtable + ' where ' + @searchtype + ' like % ' ' ' + rtrim(@searchdata) + ' ' ' % order by ' + @searchid+ ' desc '
------解决方案--------------------
除了要在%前後前後兩個單引號外,%號前後的空格也要去掉。