如果(可选)参数为null,则选择none

时间:2013-04-12 11:29:06

标签: sql sql-server-2008 select

这是事情: 我有一张桌子 DailyContent(dailyContentId,userId,weekDayId,eventId)  其中我存储了特定日期的项目(对于每个用户)。 天数分为不同的事件(每天更多事件)。 我想做的是选择项目(对于一个事件),但是不同的天数。 天有ID从1到7.如果天被“选中”我得到dayId,否则我得到null作为输入参数。

如果选择了超过一天,则只返回所有日期共同的项目。

如果没有选择日,则不返回任何内容

我尝试过这样的事情,但我只得到一天的结果。 如果我选择超过一天,则返回NOTHING(如上所述,应返回此事件的两天存储的项目。)

DECLARE @daysCount int -- only for incitation how many days are actually set
SET @daysCount = 0
IF (@mon IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@tue IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@wed IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@thu IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@fri IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@sat IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@sun IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END

-- Insert statements for procedure here
SELECT 
    DailyContent.dailyContentId

            FROM DailyContent

    WHERE
    eventId=@eventId AND (weekDayId=@mon OR
            weekDayId=@tue OR
            weekDayId=@wed  OR
            weekDayId=@thu  OR
            weekDayId=@fri  OR
            weekDayId=@sat  OR
            weekDayId=@sun)
    GROUP BY DailyContent.dailyContentId
    HAVING (COUNT(dailyContentId) = @daysCount)

这个HAVING COUNT出了点问题。 如果我删除它,它可以正常工作,但只有选择了一天。

实际上我想要的是“如果参数为空则选择所有”。

我正在使用MS SQL server 2008。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您是否尝试使用一个额外的if condition来处理“未选择日期”的方案。 像:

IF (@daysCount<>0)
SELECT DailyContent.dailyContentId, DailyContent.itemId, title, defaultSmallImagePath
    FROM DailyContent
    LEFT OUTER JOIN
        itemsTranslations ON itemsTranslations.itemId = DailyContent.itemId
    LEFT OUTER JOIN
        itemAdditionalInformation ON itemAdditionalInformation.itemId = DailyContent.itemId
    WHERE
    eventId=@eventId AND (weekDayId=@mon OR
            weekDayId=@tue OR
            weekDayId=@wed  OR
            weekDayId=@thu  OR
            weekDayId=@fri  OR
            weekDayId=@sat  OR
            weekDayId=@sun)
    GROUP BY DailyContent.dailyContentId, DailyContent.itemId, title, defaultSmallImagePath
    HAVING (COUNT(weekDayId) = @daysCount)

答案 1 :(得分:0)

试试这个 -

DECLARE @daysCount INT
SELECT @daysCount = 
    CASE WHEN @mon IS NOT NULL THEN 1 ELSE 0 END +
    CASE WHEN @tue IS NOT NULL THEN 1 ELSE 0 END +
    CASE WHEN @wed IS NOT NULL THEN 1 ELSE 0 END +
    CASE WHEN @thu IS NOT NULL THEN 1 ELSE 0 END +
    CASE WHEN @fri IS NOT NULL THEN 1 ELSE 0 END +
    CASE WHEN @sat IS NOT NULL THEN 1 ELSE 0 END + 
    CASE WHEN @sun IS NOT NULL THEN 1 ELSE 0 END 

SELECT dc.dailyContentId
FROM dbo.DailyContent dc
WHERE eventId = @eventId 
    AND weekDayId IN (@mon, @tue, @wed, @thu, @fri, @sat, @sun)
GROUP BY DailyContent.dailyContentId
HAVING COUNT(dailyContentId) = @daysCount