SQL conditional SELECT SQL conditional SELECT sql sql

SQL conditional SELECT


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 ENDFROM    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.


You want the CASE statement:

SELECT  CASE     WHEN @SelectField1 = 1 THEN Field1    WHEN @SelectField2 = 1 THEN Field2    ELSE NULL  END AS NewFieldFROM 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.


Sounds like they want the ability to return only allowed fields, which means the number of fields returned also has to be dynamic. This will work with 2 variables. Anything more than that will be getting confusing.

IF (selectField1 = true AND selectField2 = true)BEGIN   SELECT Field1, Field2   FROM TableENDELSE IF (selectField1 = true)BEGIN   SELECT Field1   FROM TableENDELSE IF (selectField2 = true)BEGIN   SELECT Field2   FROM TableEND

Dynamic SQL will help with multiples. This examples is assuming atleast 1 column is true.

DECLARE @sql varchar(MAX)SET @sql = 'SELECT 'IF (selectField1 = true)BEGIN   SET @sql = @sql + 'Field1, 'ENDIF (selectField2 = true)BEGIN   SET @sql = @sql + 'Field2, 'END...-- DROP ', '@sql = SUBSTRING(@sql, 1, LEN(@sql)-2)SET @sql = @sql + ' FROM Table'EXEC(@sql)