1

I'm trying to construct a simple query that will allow the user to filter a list of clients based on demographic information. It seems to me that LIKE would be the simplest solution, for instance:

SELECT D.Name
FROM demographics D

WHERE D.City LIKE @cityVar
AND D.Sex LIKE @sexVar
AND D.Age LIKE @ageVar
...

Variables are passed into the query using combo boxes; therefore if the user decides not to filter based on any given parameter, I simply pass '%' to the variable, effectively escaping that line in the WHERE clause.

However, this does not work if I would like to return rows containing NULL values in filtered fields. For instance, if D.Employer has a value of NULL, the client is unemployed; but passing '%' to @employedVar (meaning that the user would like to return both employed and unemployed clients) ignores all rows where D.Employer is NULL.

How would I construct the logic of the WHERE clause in order to account for a large number of parameters while still allowing the user to escape filtering on any given parameter, all the while including NULL values when appropriate?

4

2 回答 2

1

这可能对你有用。如何null在程序中解释以表明用户想要 null. 换句话说,如果用户没有指定任何东西,让我们把所有东西都给他们一个值。所以是这样的:

SELECT ...
FROM ...
WHERE ((@parm1 IS NULL AND field1 IS NOT NULL) OR
       (field1 LIKE '%' + @parm1 + '%'))

如果用户没有指定任何内容,此查询将返回所有具有值LIKE的行,但如果他们指定了任何内容,它将运行.

这只是意味着从应用程序中,如果用户没有指定任何内容(或者在您的情况下可能指定all),您将发送null到该过程。

于 2013-09-23T19:49:06.097 回答
1

最简单的方法是做这样的事情

SELECT D.Name
FROM demographics D
WHERE (D.City LIKE @cityVar OR @cityVar == '%')
    AND (D.Sex LIKE @sexVar OR @sexVar == '%')
    AND (D.Age LIKE @ageVar OR @ageVar == '%')

重要的是不要使用类似的东西

SELECT D.Name
FROM demographics D
WHERE ISNULL(D.City. '') LIKE @cityVar
    AND ISNULL(D.Sex, '') LIKE @sexVar
    AND ISNULL(D.Age, '') LIKE @ageVar

将值传递给函数将使 SQL Server 无法使用您在这些列上可能拥有的任何索引。这将导致低效的查询计划和较差的性能。

于 2013-09-23T19:52:13.277 回答