我目前有以下查询连接到3个数据源,这些数据源允许NULL值,可以任意组合使用来查询数据库以过滤结果。到目前为止,这对于@Employee和@Project工作正常,因为它们是字符串,但@Week_Ending,作为DataTime值,我无法解决如何执行此操作。目前,如果@WeekEnding值为null,则不返回任何记录,但如果输入了有效日期,则可以正常工作。
SELECT Week_Ending, Employee, Project FROM Times WHERE (Project LIKE ISNULL(@Project, '%')) AND (Employee LIKE ISNULL(@Employee, '%')) AND (Week_Ending = CONVERT(datetime, @WeekEnding, 103))
我找到了类似问题的解决方案,但他们都使用两个日期之间的范围内的结果,而不是单个日期,这就是我被困住的地方。
我想在SQL查询中保留所有逻辑,而不是使用后面的代码。
答案 0 :(得分:3)
这是catch-all query。对于一些条件,我认为您可以使用AND-OR
条件实现此目的:
SELECT
Week_Ending, Employee, Project
FROM Times
WHERE
(@Project IS NULL OR Project LIKE @Project)
AND (@Employee IS NULL OR Employee LIKE @Employee)
AND (@WeekEnding IS NULL OR Week_Ending = @WeekEnding)
注意,我将ISNULL()
替换为[column] IS NULL
,以便您的WHERE
条件成为SARGable。
答案 1 :(得分:0)
尝试下面的一个:
SELECT Week_Ending, Employee, Project FROM Times
WHERE
(Project LIKE ISNULL(@Project, '%'))
AND (Employee LIKE ISNULL(@Employee, '%'))
AND (Week_Ending = (case when @WeekEnding is null then Week_Ending else @WeekEnding end))