We help IT Professionals succeed at work.
Get Started

conditional SQL output

167 Views
Last Modified: 2017-11-12
Any way to write a query that will conditionally include a column?

I know that a Case statement can be used to control output, but
this is a little different.

For example, there is a column that contains some number of  1 character codes.
Let's say:   Optionscolumn  contains "ABCDEFG"

CASE WHEN Optionscolumn  like '%A%'  THEN 'yes' else ''  END  As ContainsA
CASE WHEN Optionscolumn  like '%B%'  THEN 'yes'  else ''  END  As ContainsB

That words just fine, but in the case of no value, I want no column at all included.
So, if   Optionscolumn  is not like '%A%'  then the column  "ContainsA" is not in the query results at all.

Reason is that there are over 30 possible values, and I only want to include the columns for
values found, which would be around 5 or 6.  I don't want 25 or so empty columns.

I've looked and tried, can't figure it out.

Since the columns needed would be different on different rows, maybe it's not possible, and
the only way is to  make a temp table and drop  any columns that are entirely empty?

Any thoughts?
Thanks!
Comment
Watch Question
Database Expert
Awarded 2016
Top Expert 2016
Commented:
This problem has been solved!
Unlock 1 Answer and 16 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE