-1

I want to select columns from a table conditionally,I Just followed this link,

SELECT ID,(CASE WHEN @check=0
          THEN Teacher END) 'Teacher'
FROM Register

Result when @check =1

---------------------
|   ID   | Teacher  |
---------------------
|   10   |  NULL    |
|   20   |  NULL    |
--------------------

In this case I don't want to select Teacher Column,How to do this?

If it is not possible How to delete column which has null value for all row ?

Community
  • 1
  • 1
mass
  • 612
  • 5
  • 7

2 Answers2

2

Use a IF ELSE condition

IF @check = 0
BEGIN
    SELECT ID, Teacher 'Teacher'
    FROM Register
END
ELSE
BEGIN
    SELECT ID FROM Register
END

OR use a dynamic query like below

DECLARE @qryStr VARCHAR(2000)
DECLARE @check INT =0
SET @qryStr = 'SELECT ID '+CASE WHEN @check=0 THEN ',Teacher' ELSE '' END +' FROM Register'
PRINT @qryStr
EXEC(@qryStr)
0

This dynamical qry is not good idea. You should rewrite your solution or denormalize your tables.

Variant 1:

declare @removeCol1 bit = 1
declare @removeCol3 bit = 1

declare @qry varchar(4000) = 'select col1, col2, col3, col4, col5 from dbo.yourtable'

if @removeCol1 = 1 set @qry = replace(replace(@qry, 'col1,', ''), 'col1', '')
if @removeCol3 = 1 set @qry = replace(replace(@qry, 'col3,', ''), 'col3', '')

print @qry
exec (@qry)

Variant 2: Use pivot on your table and filter properly. But your example isn't enought for example query.

Deadsheep39
  • 561
  • 3
  • 16