0

我正在构建一个系统,用户可以在论坛中按性别、年龄语言、用户兴趣搜索用户。

我有这个存储过程:

ALTER PROCEDURE dbo.FindFriends
    (
    @language int,
    @country nvarchar(50),
    @sex int,
    @ageFrom int,
    @ageTo int,
    @category nvarchar(50)
    )
AS
    SELECT u.*, cat.*
    FROM  [User] AS u
    INNER JOIN categories AS cat ON u.user_id=cat.user_id 
    WHERE (age_presenentation BETWEEN @ageFrom AND @ageTo) AND lingo=@language AND sex=@sex AND cat.category_name=@category

这个声明是我想要的。但有时,用户可能不会输入某些字段。例如,用户可能仅按类别搜索用户。这将导致没有用户出现,因为我使用的是“与”运算符。有没有办法组合逻辑,这样如果任何 sql 变量(例如@category、@angeTo)为空,语句将不包含它们?

4

2 回答 2

2

这取决于您所说的“空”是什么意思。如果你的意思是 NULL,那么试试这个:

WHERE age_presenentation BETWEEN @ageFrom AND @ageTo
AND (lingo=@language OR @language IS NULL)
AND (sex=@sex OR @sex IS NULL) 
AND (cat.category_name=@category OR @category IS NULL)
于 2012-04-27T17:12:17.240 回答
2

我遇到过很多次。

尝试:

WHERE (age_presenentation BETWEEN @ageFrom AND @ageTo)
AND ((@language IS NULL) OR (lingo=@language))
AND ((@sex IS NULL) OR (sex=@sex))
AND ((@category IS NULL) OR (cat.category_name=@category))

You can apply the same logic to the @ageFrom as well:
((@ageFrom IS NULL) OR (age_presenentation BETWEEN @ageFrom AND @ageTo))

但这可能是太多的记录。

于 2012-04-27T17:16:12.373 回答