1

使用 SQL Server 2008R2,我这里有一个简单的查询:

SELECT *
FROM ItemData  
WHERE FREETEXT(Title, '"' + @OriginalSearchTerm + '"')   
AND  ( WebsiteID=@WebsiteID AND GeoCity = @GeoCity  AND GeoState = @GeoState )  
ORDER BY ItemListID DESC 

@GeoCity当and有一个有效值时,这一切都很好@GeoState。然而,会有一些场景是@GeoCity = -1和/或@GeoState = -1

我宁愿不为这些情况编写完整的单独查询,尽管这样可以正常工作。

如何优化当前查询来做到这一点?

谢谢。

4

2 回答 2

0

我不确定您希望查询在何时@GeoCity = -1和/或@GeoState = -1. 假设您想在这种情况下排除GeoCity = @GeoCity和/或GeoState = @GeoState条件,这是查询:

SELECT *
FROM ItemData  
WHERE FREETEXT(Title, '"' + @OriginalSearchTerm + '"')   
AND  ( WebsiteID=@WebsiteID AND 
    (@GeoCity = -1 OR GeoCity = @GeoCity)  AND
    (@GeoState = -1 OR GeoState = @GeoState) )  
ORDER BY ItemListID DESC 
于 2012-08-07T16:02:31.940 回答
0

-- 这可能更有效,因为 OR 语句为每个 OR 语句执行块。

SELECT *
FROM ItemData  
WHERE FREETEXT(Title, '"' + @OriginalSearchTerm + '"')   
AND  ( WebsiteID=@WebsiteID AND 
    (GeoCity = ISNULL(@GeoCity,-1)) AND
    (GeoState = ISNULL(GeoState,-1))
ORDER BY ItemListID DESC 
于 2012-08-09T12:30:58.523 回答