Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL conditional SELECT

I would like to create a stored procedure with parameters that indicate which fields should be selected.

E.g. I would like to pass two parameters "selectField1" and "selectField2" each as bools.

Then I want something like

SELECT  if (selectField1 = true) Field1 ELSE do not select Field1  if (selectField2 = true) Field2 ELSE  do not select Field2  FROM Table 

Thanks Karl

like image 748
Karl Avatar asked Jun 24 '09 13:06

Karl


People also ask

How do I select conditional in SQL?

You can specify a condition by typing the column name, then a comparison operator, then a number or string. The most common comparison operators are: >, <, >=, <=, =, and != . You can filter to see only results where multiple conditions are true by combining them with an AND operator.

Can we use select statement in if condition in SQL?

It is like a Shorthand form of CASE statement. We can conveniently use it when we need to decide between two options. There are three parts in IIF statement, first is a condition, second is a value if the condition is true and the last part is a value if the condition is false.


2 Answers

In SQL, you do it this way:

SELECT  CASE WHEN @selectField1 = 1 THEN Field1 ELSE NULL END,         CASE WHEN @selectField2 = 1 THEN Field2 ELSE NULL END FROM    Table 

Relational model does not imply dynamic field count.

Instead, if you are not interested in a field value, you just select a NULL instead and parse it on the client.

like image 187
Quassnoi Avatar answered Sep 28 '22 04:09

Quassnoi


You want the CASE statement:

SELECT   CASE      WHEN @SelectField1 = 1 THEN Field1     WHEN @SelectField2 = 1 THEN Field2     ELSE NULL   END AS NewField FROM Table 

EDIT: My example is for combining the two fields into one field, depending on the parameters supplied. It is a one-or-neither solution (not both). If you want the possibility of having both fields in the output, use Quassnoi's solution.

like image 30
Welbog Avatar answered Sep 28 '22 02:09

Welbog