You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jsTree+SQL Server构建树时,#转int类型报错的解决方法

解决SQL Server中jsTree树结构查询的类型转换错误

错误原因是你的CASE表达式中两个分支返回的数据类型不统一:当满足条件时返回字符串'#',不满足时返回int类型的mod_principal。SQL Server会尝试将字符串转换为int类型,从而触发"Conversion failed when converting the varchar value '#' to data type int"错误。

只需将mod_principal转换为字符串类型,让CASE表达式的结果统一为varchar类型即可解决问题,修正后的查询语句如下:

select 
    mod_id as id,
    (case 
        when (mod_principal is null or mod_principal = 0) then '#' 
        else CAST(mod_principal AS VARCHAR(20)) 
    end) as parent, 
    mod_modulo as text,
    mod_vista 
from crediguate.dbo.modulo m 
order by m.orden

你也可以使用CONVERT函数替代CAST,效果一致:

select 
    mod_id as id,
    (case 
        when (mod_principal is null or mod_principal = 0) then '#' 
        else CONVERT(VARCHAR(20), mod_principal) 
    end) as parent, 
    mod_modulo as text,
    mod_vista 
from crediguate.dbo.modulo m 
order by m.orden

修改后,根节点的父标识会返回'#',非根节点的父ID以字符串形式返回,完全符合jsTree的树结构数据要求,同时避免了SQL Server的类型转换错误。

内容的提问来源于stack exchange,提问作者bendroide

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 02:10:52