带有变量WHERE的SELECT语句

时间:2014-06-09 09:50:55

标签: sql-server tsql select case where

我正在尝试创建一个select语句,其中包含一个可互换的where语句,我有2次尝试不能显示你尝试理解我想要实现的目标

变量@holidayType确定用户预订了哪种类型的假期,我希望它还能确定运行哪个WHERE语句

以下是我的第一次尝试

    IF @HolidayType = 'P'
        BEGIN
           WHERE    Holidays.Type <> 'A'
           AND  Holidays.Type <> 'DE'
        END
    ELSE
        BEGIN
            IF @HolidayType = 'A'
                BEGIN
                    WHERE   Holidays.Type <> 'P'
                    AND     Holidays.Type <> 'DE'
                END
            ELSE
                BEGIN
                    WHERE Holidays.status <> 'DE' 
                END
        END

以下是我的第二次尝试(更清楚一点)

    WHERE
    (
    CASE @HolidayType
        WHEN 'A' THEN (Holidays.Type <> 'P' AND Holidays.Type <> 'DE')
        WHEN 'P' THEN (Holidays.Type <> 'A' AND Holidays.Type <> 'DE')
        WHEN 'F' THEN (Holidays.status <> 'DE')
    END
    )

在他们两个之前的选择相对简单,只是添加了Where语句,这对我来说很难。

3 个答案:

答案 0 :(得分:2)

WHERE
  (@HolidayType = 'A' AND Holidays.Type <> 'P' AND Holidays.Type <> 'DE')
  OR 
   (@HolidayType = 'P' AND Holidays.Type <> 'A' AND Holidays.Type <> 'DE')
  OR 
  (@HolidayType = 'F' AND Holidays.status <> 'DE')

答案 1 :(得分:1)

尝试使用:

 WHERE (@HolidayType = 'A' AND Holidays.Type <> 'P' AND Holidays.Type <> 'DE') OR
       (@HolidayType = 'P' AND Holidays.Type <> 'A' AND Holidays.Type <> 'DE') OR
       (@HolidayType = 'F' AND Holidays.status <> 'DE')

答案 2 :(得分:1)

我提出以下解决方案。或许作者会更清楚,因为它接近他的询问:

WHERE
    (
    CASE @HolidayType 
        WHEN 'A' THEN CASE WHEN (Holidays.Type <> 'P' AND Holidays.Type <> 'DE') THEN 1 ELSE 0 END
        WHEN 'P' THEN CASE WHEN (Holidays.Type <> 'A' AND Holidays.Type <> 'DE') THEN 1 ELSE 0 END
        WHEN 'F' THEN CASE WHEN (Holidays.status <> 'DE') THEN 1 ELSE 0 END
    END = 1
    )