使用SQL中的Case语句进行级联下拉列表

时间:2014-04-04 14:34:57

标签: asp.net sql sql-server tsql

我有前端应用程序,用户从下拉框中选择城市名称或从另一个下拉框中选择州名称。如果用户从状态下拉列表中选择ALL,则查询应返回所有状态,并且对于City,同样的事情也是如此。该表具有其他信息,如邮政编码,因此查询应始终根据用户选择返回结果。该表非常庞大,超过100k行,因此我希望在检查条件时有效执行查询。此查询的问题是,如果我从州下拉列表中选择加利福尼亚,并且我想从城市下拉列表中选择LA,则查询将不起作用。请帮忙。谢谢 这是我的代码:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [MJX].[spx_Get_SL]
      @Filter_State VARCHAR(50),
      @Filter_City VARCHAR(50)
AS
BEGIN
      SET NOCOUNT ON;

      IF @Filter_State <> 'ALL' 
            SELECT * FROM myTable  WHERE State = @Filter_State

   ELSE IF  @Filter_City <> 'ALL'
        SELECT * from myTable WHERE City=@Filter_City

      ELSE
        SELECT * from myTable
END

2 个答案:

答案 0 :(得分:0)

您应该将参数值组合到一个查询中:

select * from myTable 
Where (City = @FilterCity or @FilterCity = 'ALL') 
and (State = @FilterState or @FilterState = 'ALL')

稍微更优选的选项可以避免参数嗅探并稍微优化查询:

ALTER PROCEDURE [MJX].[spx_Get_SL]
      @Filter_State VARCHAR(50),
      @Filter_City VARCHAR(50)
AS

BEGIN

DECLARE @LocFilter_State VARCHAR(50);
DECLARE @LocFilter_Cty VARCHAR(50);

SELECT @LocFilter_State = CASE WHEN @Filter_State = 'ALL' THEN NULL else @Filter_State END;
SELECT @LocFilter_City = CASE WHEN @Filter_City = 'ALL' THEN NULL else @Filter_City END;

SELECT * from MyTable Where City = ISNULL(@LocFilter_City,City) AND State = ISNULL(@LocFilter_State,State);

END

答案 1 :(得分:0)

您可以在Case子句中使用Where。所以我正在检查变量的值,然后选择适当的列或传递1

SELECT *
FROM myTable
WHERE CASE 
        WHEN @Filter_State <> 'ALL'
            THEN STATE
        ELSE 1
        END = CASE 
        WHEN @Filter_State <> 'ALL'
            THEN @Filter_State
        ELSE 1
        END
    AND CASE 
        WHEN @Filter_City <> 'ALL'
            THEN City
        ELSE 1
        END = CASE 
        WHEN @Filter_City <> 'ALL'
            THEN @Filter_City
        ELSE 1
        END