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

动态SQL向case语句传递字符串参数出现Invalid Column Name报错求助

问题根因

该报错是动态SQL拼接逻辑错误导致,本应作为字符串常量的abc被SQL解析器识别为了列名标识符,结合你的代码还有两个常见触发点:

  • 代码中用到的@sourcekey1、@sourcename变量未提前声明赋值,如果@sourcekey1被误赋值为abc,拼接后会生成src.abc的字段引用,直接触发列不存在的报错
  • 如果你实际运行的代码中拼接@system1时没有加外层的转义单引号,拼接后会生成abc = 'abc'的逻辑,abc会被直接识别为列名
  • 直接拼接字符串构造动态SQL本身就极易出现转义错误、SQL注入风险,更推荐参数化写法

方案1:修正现有拼接逻辑(仅作临时修复)

如果要保持现有拼接写法,先补全变量声明,拼接完成后先打印完整SQL校验语法:

declare @sqlsystem1 nvarchar(MAX)
       ,@system1 varchar(100) = 'abc'
       -- 按实际业务修改以下两个变量的取值
       ,@sourcekey1 varchar(100) = '你要引用的源表真实字段名'
       ,@sourcename varchar(100) = '你要查询的真实表名'
       ,@fullsql nvarchar(MAX);

set @sqlsystem1 ='case when src.uid_system_of_record = ''1'' and ''' + @system1 + ''' = ''abc'' then ''201''
                       when src.uid_system_of_record = ''2'' and ''' + @system1 + ''' = ''abc'' then ''202''
                       when src.uid_system_of_record = ''3'' and ''' + @system1 + ''' = ''abc'' then ''203''
                  else src.uid_system_of_record end';

set @fullsql = '
select convert(binary(32),hashbytes(''SHA2_256'', 
concat(
isnull(rtrim(convert(varchar(100), src.' + @sourcekey1 + ')),''NA''),
''|'', isnull(rtrim(convert(varchar(100),' + @sqlsystem1 + ')),''NA''), 
''|'', isnull(rtrim(convert(varchar(100), src.id)),''NA'')
)),0) as key_column 
from ' + @sourcename + ' src 
';

-- 先打印SQL,复制到查询窗口单独执行就能快速定位语法问题
print @fullsql;
exec sp_executesql @fullsql;

如果你的业务逻辑本就是要引用@system1作为列名判断值等于abc,去掉@system1拼接时外层的转义单引号即可,同时要保证@system1的取值是源表真实存在的列名。


方案2:改用参数化动态SQL(推荐)

不需要作为动态标识符的变量统一通过sp_executesql参数传入,彻底避免转义错误:

declare @system1 varchar(100) = 'abc'
       -- 按实际业务修改以下两个变量的取值
       ,@sourcekey1 varchar(100) = '你要引用的源表真实字段名'
       ,@sourcename varchar(100) = '你要查询的真实表名'
       ,@fullsql nvarchar(MAX);

-- 只有表名、字段名这类标识符需要拼接,值变量全部用参数占位
set @fullsql = '
select convert(binary(32),hashbytes(''SHA2_256'', 
concat(
isnull(rtrim(convert(varchar(100), src.' + @sourcekey1 + ')),''NA''),
''|'', isnull(rtrim(convert(varchar(100),
    case 
        when src.uid_system_of_record = ''1'' and @system1 = ''abc'' then ''201''
        when src.uid_system_of_record = ''2'' and @system1 = ''abc'' then ''202''
        when src.uid_system_of_record = ''3'' and @system1 = ''abc'' then ''203''
        else src.uid_system_of_record 
    end
)),''NA''), 
''|'', isnull(rtrim(convert(varchar(100), src.id)),''NA'')
)),0) as key_column 
from ' + @sourcename + ' src 
';

-- 传参执行
exec sp_executesql @fullsql, N'@system1 varchar(100)', @system1 = @system1;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:57:01