当前位置: 代码迷 >> Sql Server >> 在将varchar值'and time between '2012-04-17' and '2012-04-20''转换成数据类型 int 时失败。该如何解决
  详细解决方案

在将varchar值'and time between '2012-04-17' and '2012-04-20''转换成数据类型 int 时失败。该如何解决

热度:222   发布时间:2016-04-27 13:14:51.0
在将varchar值'and time between '2012-04-17' and '2012-04-20''转换成数据类型 int 时失败。
我的存储过程里面是这么写的
SQL code
ALTER PROCEDURE [dbo].[PRO_Priorflow_get] @strwhere varchar(500),......as beginselect @total=count(1) from PRO_Priorflow where 1=1 + @strwhere....end 


传过来的查询条件是‘and recordtime between '2012-04-17 00:00:00' and '2012-04-20 23:59:59' ’
报错了,[email protected]@[email protected]??件,如果写成
SQL code
ALTER PROCEDURE [dbo].[PRO_Priorflow_get] @strwhere varchar(500),@begintime varchar(500),@endtime varchar(500),@no int......as beginselect @total=count(1) from PRO_Priorflow where 1=1 and time between @begintime and @endtime and [email protected]....end 
时由于前台没有选择no的查询,后台查不到数据,求怎么解决的思路

------解决方案--------------------
SQL code
declare @total int, @sqls nvarchar(4000) set @sqls='select @a=count(*) from tableName  where 1=1 and time [email protected][email protected]+'and [email protected]exec sp_executesql @sqls,[email protected] int output',@total output select @total
------解决方案--------------------
可以考虑使用动态SQL语句
SQL code
@sql = '.....code......'exec( @sql )
------解决方案--------------------
SQL code
declare @total int, @sqls nvarchar(4000) set @sqls='select @a=count(*) from tableName  where 1=1 and time [email protected][email protected]+'and no='+ltrim(@no)exec sp_executesql @sqls,[email protected] int output',@total output select @total
------解决方案--------------------
你要选择动态拼接,没有传参数的条件就不要加。
------解决方案--------------------
应该是and recordtime between '2012-04-17 00:00:00' and '2012-04-20 23:59:59' ’
的问题
应该是' and recordtime between '''+'2012-04-17 00:00:00'+'''+' and '''+'2012-04-20 23:59:59'''
------解决方案--------------------
不要用拼串的方式,执行效率不好,而且如果微调一下,还得去改前端程序
这的需求有些像报表查询一样,根据条件来查询,如果没有选择哪个条件,where语句之后就不带它
很多人都根据选择的条件个数动态的去构建不同的SQL语句,前端程序会写的太复杂
每个成熟的业务系统都有一个统一的解决方案,可以用SQL探查器跟踪分析他们的查询行为看是怎么解决的
  相关解决方案