MySQL带@变量的SQL查询命令行正常,C#调用报执行致命错误如何解决?
问题原因
- MySql官方.NET驱动默认将SQL中
@开头的标识符判定为需要传入的命令参数,你代码中用到的@running_total是MySQL自定义用户变量,驱动找不到对应参数配置就会触发执行错误。 - 你提供的C#代码中,SQL字符串末尾多了一个多余的右括号
),本身存在SQL语法错误,直接执行也会报错。
解决方案
- 先修正SQL语法错误,删除查询语句末尾多余的右括号。
- 在你的数据库连接字符串中添加
Allow User Variables=True参数,开启驱动对MySQL用户变量的支持,驱动就不会再把自定义的@变量识别为待传入参数。参考连接字符串格式:
server=127.0.0.1;user=root;password=你的密码;database=你的库名;Allow User Variables=True;
- 可选优化(适配MySQL 8.0+版本):
你可以直接用窗口函数替代自定义变量实现累计余额计算,完全规避用户变量的兼容问题,改造后的参考SQL如下:
-- 先计算期初余额 SET @init_balance = (select sum(case when tr_type='1' then tr_qty else -(tr_qty) end) from tblinvtransaction where tr_date<'2021-09-01' and tr_itemcode = '01'); SELECT tr_date, tr_invno, particulars, received, issued, @init_balance + SUM(balance) OVER(ORDER BY tr_date, tr_type) AS running_balance FROM (SELECT tr_date, tr_invno, tr_accounthead as particulars, case when tr_type=1 then tr_qty else 0 end received, case when tr_type=2 then tr_qty else 0 end issued, case when tr_type=1 then tr_qty else -(tr_qty) end balance FROM tblinvtransaction where tr_date between '2021-09-01' and '2021-09-09' and tr_itemcode = '01' ) t ORDER BY t.tr_date, t.tr_type
内容的提问来源于stack exchange,提问作者Muhammad Saleem
相关产品推荐
相关产品推荐

