-1

I have a variable @variable 1 [bit] which tells me either to exclude or not certain data (based on a different value) from a select statement.

Simple example I have a table (plants) with 2 columns :

Name_of_the_plant, numbers

I have a report in which the user should be able to declare a value @WithoutTrees and I should be able to present the result without the trees, based on their names(for which I have a nomenclature).

I want to be able to run the select query based in two ways based on the variable WithoutTrees.

  1. When the bit value is 0: SELECT * FROM Plants
  2. When the bit value is 1: SELECT * FROM Plants where Name_of_the_plant not in ('Oak', 'Pine')
Amira Bedhiafi
  • 8,088
  • 6
  • 24
  • 60
  • 2
    What have you tried? This seems like a "Simple" `IF` would suffice. – Thom A Nov 18 '19 at 11:28
  • use proper database tag! – Prashant Pimpale Nov 18 '19 at 11:30
  • 3
    Although this could be accomplished with an `OR` in the `WHERE` clause, a `UNION ALL` may perform better: `SELECT * FROM Plants WHERE @variable = 0 UNION ALL SELECT * FROM Plants WHERE @variable = 1 AND Name_of_the_plant NOT IN ('Oak', 'Pine');` – Dan Guzman Nov 18 '19 at 11:39
  • Possible duplicate of [How can I use optional parameters in a T-SQL stored procedure?](https://stackoverflow.com/questions/3415582/how-can-i-use-optional-parameters-in-a-t-sql-stored-procedure) – EzLo Nov 18 '19 at 12:50

1 Answers1

2

SQL Fiddle

MS SQL Server 2017 Schema Setup:

CREATE TABLE Plants(
    Name_of_the_plant VARCHAR(255),
    numbers INT
);

INSERT INTO Plants(Name_of_the_plant,numbers)VALUES('Oak', 100),
                                                  ('Pine', 56),
                                                  ('XXX', 90)

Query 1:

BEGIN
DECLARE @variable1 bit 
SET @variable1=1

IF (@variable1 = 0)
BEGIN 
SELECT * FROM Plants
END
ELSE
BEGIN
SELECT * FROM Plants where Name_of_the_plant NOT IN ('Pine','Oak')
END
END

Results:

| Name_of_the_plant | numbers |
|-------------------|---------|
|               XXX |      90 |
Amira Bedhiafi
  • 8,088
  • 6
  • 24
  • 60
  • Thank you very much. One more question, what if I want have 2 variables(again bit) and I want to specify the select statements based on every combination between "True" and "False" in those variables? Could I write "If (@variable1 = 0) AND (@variable2 = 0)"? – Stoycho Dimitrov Nov 25 '19 at 13:07
  • @StoychoDimitrov what are your conditions ? – Amira Bedhiafi Nov 25 '19 at 13:28
  • Using the same example: The user is choosing to view report with all plants, or select two variables "@WithoutTrees" and "@WithoutFertilePlants" . The resu;ts that is received by the "SELECT" statement must be based on the both values. Both could be "true", both could be "false" or they could be different "true" and "false". – Stoycho Dimitrov Nov 26 '19 at 07:22