1、问题描述
存储过程GetTableCompare,三个参数输入参数
1.1 、传入条件参数: and myclassdate between ‘2014-12-01‘ and ‘2014-12-31‘ and classname like ‘%夜班%‘ and deptid in
(1,2,3,4,5,8,9,11,13,14,18,19,20,21,23,25,26,27,28,29,30,31,32,33,34)
通过代码调用时,总是报语法错误(少))
GetTableCompare
‘%早班%‘ and deptid in (1,2,3,4,5,8,9,11,13,14,18,19,20,21,23,25,26,27,28,29,30,31,32,33,3 group by 部门,classname order by classnam‘
附近有语法错误。字符串
‘%早班%‘ and deptid in (1,2,3,4,5,8,9,11,13,14,18,19,20,21,23,25,26,27,28,29,30,31,32,33,3 group by 部门,classname order by classname,部门‘
后的引号不完整。
1.2 、条件参数修改为:and my and myclassdate between ‘2014-12-01‘ and ‘2014-12-31‘ and deptid in
(1,2,3,4,5,8,9,11,13,14,18,19,20,21,23,25,26,27,28,29,30,31,32,33,34) ,正确执行不报错
procedure [dbo].[GetTableCompare](@dtTime datetime,@strW nvarchar(1000),@Flag int)
1.3 、以下是调用代码
//信息统计 public static DataTable GetCompare(DateTime dt, string strW,int type) {//调用存储过程 OleDbParameter[] parameters = new OleDbParameter[3]; parameters[0] = new OleDbParameter("@dtTime", OleDbType.VarChar); parameters[0].Value = dt.ToString("yyyy-MM-dd"); parameters[1] = new OleDbParameter("@strW", OleDbType.VarChar); parameters[1].Value = strW; parameters[2] = new OleDbParameter("@type", OleDbType.Integer); parameters[2].Value = type; DataSet ds = DB.OleDbHelper.GetDataSet("GetTableCompare", CommandType.StoredProcedure, parameters); if (ds != null && ds.Tables.Count > 0) { return ds.Tables[0]; } return null; }
2、分析
实际跟踪传入的条件strW,并没有少),语法是正确的
再次打开Sql Server Profile跟踪存储过程的执行,发现条件语句少了)
可能原因:
传入的语言类型为varchar类型,是可变长的非Unicode字符,存储输入数据字节的实际长度,例如 数据:我们1234,存储长度为2*2+4=8
而parameters[1].Size 是根据parameters[1].Value值推算的,在输入非Unicode字符时推算正确,而输入了中文后,推算的值小于实际传入的值,所以字符串被截断
这也就是传入的条件参数中仅仅包含了中文“夜班”时才报错
3、解决方法
方法一,输入参数使用OleDbType.LongVarWChar方法二:自己设定size parameters[1].Size = 500;
public static DataTable GetCompare(DateTime dt, string strW,int type) { if (!string.IsNullOrEmpty(Global.Params.strDeptIDs)) strW += " and deptid in (" + Global.Params.strDeptIDs + ") "; //调用存储过程 OleDbParameter[] parameters = new OleDbParameter[3]; parameters[0] = new OleDbParameter("@dtTime", OleDbType.VarChar); parameters[0].Value = dt.ToString("yyyy-MM-dd"); parameters[1] = new OleDbParameter("@strW", OleDbType.LongVarWChar); //方法一,输入参数使用OleDbType.LongVarWChar parameters[1].Value = strW; //parameters[1].Size = 500; //方法二,自己设定size parameters[2] = new OleDbParameter("@type", OleDbType.Integer); parameters[2].Value = type; DataSet ds = DB_Contrast.DB.OleDbHelper.GetDataSet("GetTableCompare", CommandType.StoredProcedure, parameters); if (ds != null && ds.Tables.Count > 0) { return ds.Tables[0]; } return null; }