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

如何在Proc SQL的CASE表达式中调用存储为变量值的条件表达式?

SAS宏批量变量验证:CASE表达式动态调用条件失效问题

我使用CASE表达式验证var1的值并为新变量var1_val赋值,相关规则依赖两个数据集:

  • 数据集response_options_scan的valid_values列存储var1的所有有效值;
  • 数据集response_options_select的requirement_status列定义var1的必填时机,值包括"All Records"、"Required"或"var2 contains xyz"这类动态条件。

由于代码要用于宏中批量验证数十个变量,我希望在CASE的第三个WHEN条件中直接调用requirement_status的存储值,而非硬编码条件。但硬编码写法能得到正确结果,直接SELECT调用requirement_status的写法却不符合预期。


硬编码方式(结果正确)

proc sql noprint;
    create table validate_select_test
    as select *
        ,case when var1 in (select valid_values from response_options_scan where variable="var1") then "var1 valid value"
        when var1="" and (select requirement_status from response_options_select where variable="var1") in ("All Records", "Required") then "var1 invalid value: missing" 
        when var1="" and var2 contains 'XYZ' then "var1 invalid value: missing"
        when var1="" then "var1 valid value: missing"
        else "var1 invalid value"
        end as var1_val format=$100.
    from validate_select;
quit;
var1var2var1_val
Avar1 valid value
ABCvar1 valid value: missing
ABC:XYZvar1 invalid value: missing

SELECT调用方式(结果不符合预期)

注:response_options_select中variable="var1"对应的requirement_status值为"var2 contains 'XYZ'",预期var2不含XYZ且var1为空时,var1_val应为"var1 valid value: missing"。

proc sql noprint;
    create table validate_select_test
    as select *
        ,case when var1 in (select valid_values from response_options_scan where variable="var1") then "var1 valid value"
        when var1="" and (select requirement_status from response_options_select where variable="var1") in ("All Records", "Required") then "var1 invalid value: missing" 
        when var1="" and (select requirement_status from response_options_select where variable="var1") then "var1 invalid value: missing"
        when var1="" then "var1 valid value: missing"
        else "var1 invalid value"
        end as var1_val format=$100.
    from validate_select;
quit;
var1var2var1_val
Avar1 valid value
ABCvar1 invalid value: missing
ABC:XYZvar1 invalid value: missing

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 10:05:28