日期:2014-05-17  浏览次数:20492 次

SQL多条件查询存储过程问题


CREATE PROCEDURE [sp_SelFindResources5]
--@Memberid int,--会员ID 
@WarehouseRN varchar,--仓单号
@Commodity nvarchar, --品名
@Specifications varchar,--规格
@Steelmill nvarchar,--钢厂
@Unitprice int,--单价
@Pagecount int,--每页行数
@pagesize int --第几页
AS
set nocount on
declare @acount int,
@sqlwhere varchar(500)

set @acount=@Pagecount*@pagesize

if(@WarehouseRN='')
set @sqlwhere=@sqlwhere+'and WarehouseRN like ''%'+@WarehouseRN+'%'''
if(@WarehouseRN<>'')
set @sqlwhere=@sqlwhere+'and WarehouseRN like '+@WarehouseRN+'%'''

if(@Commodity='1')
set @sqlwhere=@sqlwhere+'and Commodity like''%'''
if(@Commodity<>'1')
set @sqlwhere=@sqlwhere+'and Commodity ='+@Commodity

if(@Specifications='')
set @sqlwhere=@sqlwhere+'and Specifications like ''%'+@Specifications+'%'''
if(@Specifications<>'')
set @sqlwhere=@sqlwhere+'and Specifications like '+@Specifications+'%'''

if(@Steelmill='')
set @sqlwhere=@sqlwhere+'and Steelmill like ''%'+@Steelmill+'%'''
if(@Steelmill<>'')
set @sqlwhere=@sqlwhere+'and Steelmill like '+@Steelmill+'%'''

if(@Unitprice='0')
set @sqlwhere=@sqlwhere+'and Unitprice like''%'''
if(@Unitprice<>'0')
set @sqlwhere=@sqlwhere+'and Unitprice ='+@Unitprice+''

EXEC( 'select * from VIEW_sp_SelFindResources5 where 1=1'+@sqlwhere)


前台代码都没错,问题出在存储过程中
装载的时候,显示的是全部数据,已经显示了

前台输入 单价:111
提示:[Exception: System.Data.SqlClient.SqlException: 将 varchar 值 ''' 转换为数据类型为 int 的列时发生语法错误。

前台选择或输入其他数据时,没有反应,还是显示全部

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

set @sqlwhere=@sqlwhere+'and Unitprice ='+@Unitprice+''
--类似这种整型参数的都改过来
set @sqlwhere=@sqlwhere+'and Unitprice ='+convert(varchar(100),@Unitprice)+''

------解决方案--------------------
@Unitprice既然定义为int,为什么要把它当成varchar来用呢?

set @sqlwhere=@sqlwhere+'and Unitprice ='+@Unitprice+''里的@Unitprice替换为
convert(varchar(30),@Unitprice)