繁体   English   中英

动态更改SQL查询中的where子句

[英]Dynamically change the where clause in the SQL Query

我在需要调用.net核心API并返回结果的地方构建Angular应用程序。 如下所示,角度应用中有两个字段

在此处输入图片说明

可以选择两个字段,可能只是一个字段将被选择,并且需要根据选择从API获取结果

如果两个字段都被选中,我的查询如下

  Select prj_number,location from sTable where r_proj = '000634' AND sdate = '2019-07-01' group by prj_number,location

如果只是选择了报告项目,那么

 Select prj_number,location from sTable where r_proj = '000634'  group by prj_number,location

同样,对于持续时间,根据Angular的选择动态更改where子句。

我想根据像这样的选择在Angular中构建一个字符串表达式

     string para = r_proj = '000634' AND sdate = '2019-07-01' 

并像这样传递给查询

  Select prj_number,location from sTable where @para  group by prj_number,location

但这没有用,我收到类似'An expression of non-boolean type specified in a context where a condition is expected, near 'group'.''An expression of non-boolean type specified in a context where a condition is expected, near 'group'.'错误'An expression of non-boolean type specified in a context where a condition is expected, near 'group'.' 看起来我无法传递表达式作为参数。 我如何应对这种情况

将每个参数设置为“可选”,如下所示:

DECLARE @projIdFilter varchar(10) = null
DECLARE @sdateFilter datetime = null

SELECT prj_number,location 
FROM sTable 
WHERE (@projIdFilter is null or r_proj = @projIdFilter) -- parenthesis are important
  AND (@sdateFilter is null or sdate = @sdateFilter)
GROUP BY prj_number,location

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM