ef oracle参数化问题
并非所有变量都已绑定
假如一个sql是这样的
string sql =@" select id from a where date between :StartDate and :EndDate union all select id from b where date between :StartDate and :EndDate "
这个时候创建 DbParameter 列表时如果只有两个参数,程序就会报”并非所有变量都已绑定“的错误
List<DbParameter> dbPara = new List<DbParameter> { DbAccess.CreateParameter(":StartDate", DbType.DateTime,DateTime.Parse(dt.AddDays(1 - dt.Day).ToString("yyyy-MM-dd 00:00:00"))), DbAccess.CreateParameter(":EndDate", DbType.DateTime, dt) };
虽然sql中两个变量值一样,但是 defaultDB.Database.SqlQuery<T>(dynamicSql, parameters)执行的时候,应该会重新定义4个不同的变量,所以会报错!
解决办法很简单,参数列表定义成四个就行了
List<DbParameter> dbPara = new List<DbParameter> { DbAccess.CreateParameter(":StartDate", DbType.DateTime,DateTime.Parse(dt.AddDays(1 - dt.Day).ToString("yyyy-MM-dd 00:00:00"))), DbAccess.CreateParameter(":EndDate", DbType.DateTime, dt), DbAccess.CreateParameter(":StartDate", DbType.DateTime,DateTime.Parse(dt.AddDays(1 - dt.Day).ToString("yyyy-MM-dd 00:00:00"))), DbAccess.CreateParameter(":EndDate", DbType.DateTime, dt) };
ora-01847:月份中日的值必须介于 1 和当月最后一日之间
我们都知道,如果sql中参数日期不合法,会报这个错误,但是我程序中,日期都是datetime类型,不存在这种情况,找了好久终于知道什么原因了。
先看出现错误时的sql和参数列表定义
List<DbParameter> dbParaBYRY = new List<DbParameter> { DbAccess.CreateParameter(":PARM_DANGQIANKS",DbType.AnsiString, YongHuxx.KeShiID), DbAccess.CreateParameter(":PARM_KaiShiSJ", DbType.DateTime,DateTime.Parse(dt.AddDays(1 - dt.Day).ToString("yyyy-MM-dd 00:00:00"))), DbAccess.CreateParameter(":PARM_JieShuSJ", DbType.DateTime, dt) }; sql = @"SELECT TO_CHAR(SFXM_CODE) XiangMuID, FUN_GETYLXMMC(SFXM_CODE) XiangMuMC, SUM(JE) FeiYongJE FROM ZY_PATIENT_INFORMATION A, ZY_TOTAL_FEE B, ZY_BILL_FEE C WHERE A.PATIENT_NO = B.PATIENT_NO AND B.PATIENT_NO = C.PATIENT_NO AND B.JS_NO = C.JS_NO AND PREOUT_DATE BETWEEN :PARM_KaiShiSJ AND :PARM_JieShuSJ AND A.CURR_KS = :PARM_DANGQIANKS GROUP BY SFXM_CODE, FUN_GETYLXMMC(SFXM_CODE)";
细心的童鞋会发现,参数定义的顺序和sql中出现的顺序反了,我一开始没有意识到这里会出错,参数名字和sql中名字不是一样 吗,不应该时按名字赋值吗,不过一直报上边这个错误,最后抱着试一试的态度,把sql中条件参数顺序调整了,结果成功了!
List<DbParameter> dbParaBYRY = new List<DbParameter> { DbAccess.CreateParameter(":PARM_DANGQIANKS",DbType.AnsiString, YongHuxx.KeShiID), DbAccess.CreateParameter(":PARM_KaiShiSJ", DbType.DateTime,DateTime.Parse(dt.AddDays(1 - dt.Day).ToString("yyyy-MM-dd 00:00:00"))), DbAccess.CreateParameter(":PARM_JieShuSJ", DbType.DateTime, dt) }; sql = @"SELECT TO_CHAR(SFXM_CODE) XiangMuID, FUN_GETYLXMMC(SFXM_CODE) XiangMuMC, SUM(JE) FeiYongJE FROM ZY_PATIENT_INFORMATION A, ZY_TOTAL_FEE B, ZY_BILL_FEE C WHERE A.PATIENT_NO = B.PATIENT_NO AND B.PATIENT_NO = C.PATIENT_NO AND B.JS_NO = C.JS_NO AND A.CURR_KS = :PARM_DANGQIANKS AND PREOUT_DATE BETWEEN :PARM_KaiShiSJ AND :PARM_JieShuSJ GROUP BY SFXM_CODE, FUN_GETYLXMMC(SFXM_CODE)";
所以我怀疑,这里sqlquery方法执行的时候,应该给变量重新定义临时变量了,结果sql查询按给的参数列表赋值的话,就把:PARM_DANGQIANKS 这个参数值赋值给了:PARM_KaiShiSJ,它都不是时间,所以肯定报错了。