[英]SQL Server - Query with tricky where clause
我有一个报告,用户可以在这三个值中选择一个过滤器值,并可以在单击“提交”按钮之前传递日期范围(“从日期”和“到日期”):
我想在myTable上为所选过滤器值触发选择查询。
如果用户选择第一个值(1),则查询应提供所有记录,其中dtEventDate在输入的日期范围之间。
如果用户选择第二个值(2),则查询应提供所有记录,其中dtGuestCreatedDate在输入的日期范围之间。
同样,如果用户选择第三个值(3),则查询应提供dtGuestCreatedDate大于“ To Date”的所有记录。
我的查询是这样的,
Select * from myTable
where
if '#filterValue#'='Events within Date Range'
then myTable.dtEventDate between '' and ''
else if '#filterValue#'='New Guests withing Date Range'
then myTable.dtGuestCreatedDate between '' and ''
else myTable.dtGuestCreatedDate > ''
我不知道该怎么写。
到目前为止,我可以得到在日期范围内的事件:
select * from myTable
where myTable.dtEventDate between
case when '#filterValue#'='Events Within Date Range' then '10/01/2016' end
and '11/30/2016'
但是我需要在一个where子句中检查所有三个过滤器值。
有人可以帮忙吗?
您可以根据给出的示例执行以下操作:
Select * from myTable
where
('#filterValue#'='Events within Date Range' AND myTable.dtEventDate between '' and '')
OR
('#filterValue#'='New Guests withing Date Range' AND myTable.dtGuestCreatedDate between '' and '')
OR
('#filterValue#'='New Guests Beyond Date Range' AND myTable.dtGuestCreatedDate > '')
select * from myTable
where case @filtervalue
when 'Events within daterange' then myTable.dtEventDate between ...
when 'New Guests within daterange' then ...
...
end
另外,我强烈建议您使用参数化查询来避免SQL注入攻击。 假设您的环境允许这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.