如何编写一个查询,如果一个列值不为null,则将该值与查询字符串进行比较,否则不要比较列值。
例如,我有一个tbl1,其中包含programs1和program2两列,这两列中的值可以为null或带值。我想要if语句说
if programs1 is not null, programs1=@programs and
if programs2 is not null, programs2=@programs
我的查询是这样的:
select * from tbl1 where
(programs1 is not null and programs1=@programs)
and
(program2 is not null and programs2=@programs)
但它没有按我想要的方式工作。如何为此案例编写正确的查询? TIA。
答案 0 :(得分:7)
我相信您正在寻找COALESCE
。
WHERE COALESCE(programs1, programs2) = @Programs
但是,如果您只想比较它是否有值:
-- If the column is null, ignore it. If it has a value, then
-- check that value.
WHERE (programs1 IS NULL OR programs1 = @Programs)
AND (programs2 IS NULL OR programs2 = @Programs)
此外,我认为您的意思是sql-server,因为您引用了asp.net
答案 1 :(得分:0)
select *
from tbl1
where (programs1=@programs or programs1 is null)
and (programs2=@programs or programs2 is null)
答案 2 :(得分:0)
ISNULL(programs1,programs2) = @Programs
或
(programs1 is not null and @Programs = programs1) or (programs2 is not null and @Programs = programs2)