您好我试图使用SQL字符串从访问数据库中提取查询,我很难让代码正常工作。如果我使用以下代码
" select [incident id] as incidentid, ([incident ID] &' '&[incident date]) as incisearch from incident where (@supplier is null or [stock supplier] = @supplier)"
如果输入@supplier的参数,如果我使用以下代码
,它将仅返回结果" select [incident id] as incidentid, ([incident ID] &' '&[incident date]) as incisearch from incident where ([stock supplier] is null or @supplier)"
无论输入什么参数@supplier,它都只返回null的结果。我已经尝试了今天早上这个代码的几种组合/变体,如果@supplier为null,我不能让它显示所有结果,并在输入@supplier参数时显示相关结果。有人可以告诉我我的代码在哪里错了吗?
答案 0 :(得分:4)
where ([stock supplier] is null or @supplier)
总是值得首先使用示例数据测试您的SQL。
你会发现这是一个语法错误,没有column = a or b
之类的表达式语法。相反,你需要像:
where (([stock supplier] is null) or ([stock supplier] = @supplier))
或更可能:
where ((@supplier is null) or ([stock supplier] = @supplier))
如果参数本身为null,将始终为true(返回所有行)。
答案 1 :(得分:1)
尝试使用以下代码段
select
[incident id] as incidentid,
([incident ID] &' '&[incident date]) as incisearch
from incident
where ([stock supplier]=isnull(@supplier,[stock supplier]))