Reputation: 607
A simplified example of what I need:
Table 'Transport' has 2 columns; 'Vehicle' and 'Colour'. User can filter records by either a vehicle, a colour, or both.
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")
So if the user wanted a 'red' 'bus' the query would look like:
("Select * From Transport Where Vehicle = 'bus' And Colour = 'red'")
Which would be fine and find the record if it existed.
But, if the user wanted all vehicles that were yellow the query would look like:
("Select * From Transport Where Vehicle = * and Colour = 'yellow'")
Clearly this is all in a made up syntax but this is what I want, is it possible in SQL? (Using MS SQL Server 2008)
Upvotes: 1
Views: 6762
Reputation: 181
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)
Upvotes: 0
Reputation: 1870
Yes. it is possible.just modify your query like this:
suppose your dropdown parameter is:
ddl1.val -- for transport
ddl2.val -- for color
now suppose your default ddl values is '0' or whatever for 'select all' option.now your query will be:
Select * From Transport Where (Vehicle = ddl1.val or ddl1.val='0') and
(Colour = ddl2.val or ddl2.val='0')
alternate way to do this:
Select * From Transport Where Vehicle like '%' and Colour = 'color_selected'
let me know if u want any other clarification regarding this.
Upvotes: 0
Reputation: 21
You can try something like
("Select * From Transport Where Vehicle like '%' and Colour = 'yellow'")
Upvotes: 2
Reputation: 1270061
Here are two typical ways to solve this. Assume that the user input is in the variables @vehicle
and @colour
:
where (vehicle = @vehicle or @vehicle is null) and
(colour = @colour or @colour is null)
The problem with this approach is the use of indexes. Indexing strategies have a hard time with or
. So, if you are constructing the query dynamically, then it is better to only add the clauses you want:
@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);
Upvotes: 2
Reputation: 25753
You can prepare 2nd query
("Select * From Transport Where Vehicle = * and Colour = 'yellow'")
to this
("Select * From Transport Where Vehicle = Vehicle and Colour = 'yellow'")
It's only idea how to solve your problem.
Upvotes: 2