Kivayan Kivayan - 5 months ago 15x
SQL Question

Select certain column only if condition met

I want to have a select that will not have fixed number of columns.
Collumn OptionalCollumn should be selected only if variable @check = 1

This is what I had (syntax is bad but maybe it explains my problem)

SELECT Collumn1, Collumn2,
(IF @Check = 1
BEGIN OptionalCollumn END)
FROM table

It is crucial to have it only if @Check = 1 and not having it if @Check = 0.
Is it doable?


You could do this with an IF ELSE block like this;

CREATE TABLE #table (Column1 varchar(10), Column2 varchar(10))
('column1', 'column2')

DECLARE @Check bit; SET @Check = 0

IF @Check = 1 
(SELECT Column1, Column2
FROM #table)


(SELECT Column1
FROM #table)

Change the variable from 0 to 1 for testing to see the change in number of columns.