首页 > 解决方案 > 如何编写动态Sql查询

问题描述

我有一个有 2 列的表。如果行仅包含第 1 列的值,那么我需要执行操作 a。如果它对两列都有值,我需要执行操作 b,如果行只有第 2 列,我需要执行操作操作 3。如何为此编写 SQL

标签: sqldynamic

解决方案


如果通过“操作”您的意思是“在结果集中的列中设置一个值”,那么您需要一个case表达式:

select (case when col1 is not null and col2 is null then 'a'
             when col1 is not null and col2 is not null then 'b'
             when col1 is null and col2 is not null then 'c'
        end)
from t;

推荐阅读