从table中选择column = anything

时间:2015-05-13 10:36:26

标签: sql sql-server

我需要的简化示例:

表'运输'有2列; '车载'和'颜色'。用户可以通过车辆,颜色或两者来过滤记录。

variable vehicle_choice = user_selected_vehicle (selected from a dropdown for example)
variable colour_choice = user_selected_colour

If user_selected_vehicle = nothing selected Then
    vehicle_choice = *
End if

If user_selected_colour = nothing selected Then
    colour_choice = *
End if

Select query = ("Select * From Transport Where Vehicle = vehicle_choice And Colour = colour_choice")

因此,如果用户想要一个红色' '总线'查询看起来像:

("Select * From Transport Where Vehicle = 'bus' And Colour = 'red'")

哪个会好的,如果它存在就找到记录。

但是,如果用户想要所有黄色的车辆,则查询看起来像:

("Select * From Transport Where Vehicle = * and Colour = 'yellow'")

显然,这一切都是用语法编写的,但这就是我想要的,是否可以在SQL中使用? (使用MS SQL Server 2008)

5 个答案:

答案 0 :(得分:2)

以下是解决此问题的两种典型方法。假设用户输入位于变量@vehicle@colour

where (vehicle = @vehicle or @vehicle is null) and
      (colour = @colour or @colour is null)

这种方法的问题是使用索引。索引策略很难用or。因此,如果要动态构建查询,那么最好只添加所需的子句:

@where = '1 = 1' +
         (case when @vehicle is not null then ' and vehicle = @vehicle' else '' end) +
         (case when @colour is not null then ' and colour = @colour' else '' end);

答案 1 :(得分:1)

您可以准备第二个查询

("Select * From Transport Where Vehicle = * and Colour = 'yellow'")

到这个

("Select * From Transport Where Vehicle = Vehicle and Colour = 'yellow'")

只知道如何解决问题。

答案 2 :(得分:1)

您可以尝试类似

的内容
("Select * From Transport Where Vehicle like '%' and Colour = 'yellow'")

答案 3 :(得分:0)

是。它是可能的。只需修改你的查询:

假设您的下拉参数为:

ddl1.val -- for transport
ddl2.val -- for color

现在假设您的默认ddl值为“0”或“全部选择”选项。现在您的查询将是:

 Select * From Transport Where (Vehicle = ddl1.val or ddl1.val='0') and
(Colour = ddl2.val or ddl2.val='0')

替代方法:

Select * From Transport Where Vehicle like '%' and Colour = 'color_selected'

如果您对此有任何其他澄清,请告诉我。

答案 4 :(得分:0)

declare @vehicle_choice nvarchar(255)
declare @colour_choice nvarchar(255)
set @colour_choice = 'bus'
set @colour_choice = 'blue'

Select * From Transport 
    where 1= 1 
    and Vehicle like (case when @vehicle_choice Is null or @vehicle_choice = '' then '%' else @vehicle_choice end)
    and Colour like (case when @colour_choice Is null or @colour_choice = '' then '%' else @colour_choice end)