tags:

views:

289

answers:

1

Hello,

I have a table with the following columns in table:

id, t1, t2, t3, t4

All are of type bit (There are other columns as well, however I am only showing the relevant one)

Now, I need to get the following string based on the ID:

t1 t2 t3 t4

The best I thought of would be this:

declare @t1 bit, @t2 bit...
Select @t1 = t1, @t2 = t2 from t where id = 1

declare @theString
set @theString = ''

if @t1 = 1
  set @theString = @theString + 't1 '

if @t2 = 1
  set @theString = @theString + 't2 '

...

Is there a better way to achieve this? Please note that I can not change the table. Its probably very bad formatted like that.

Thanks

A: 

I think this would do it:

DECLARE @theString varchar(100)

SELECT @theString = case t1 when 1 then 't1 ' else '' end
                  + case t2 when 1 then 't2 ' else '' end
                  + case t3 when 1 then 't3 ' else '' end
                  + case t4 when 1 then 't4 ' else '' end
 from t
 where id = 1

Might take a bit of tweaking, depending on what database system/language you are using.

Philip Kelley
ouch.... I should have thought of that. Thanks
vikasde