2009-10-01 59 views
1

我有表下面的表:SQL合併列轉換成字符串

ID,T1,T2,T3,T4

所有的類型位 的(還有其他列,以及但是我只顯示相關的一個)

現在,我需要根據ID下面的字符串

T1 T2 T3 T4

我想到的最好的將是這樣:

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 ' 

... 

有沒有更好的方式來實現這一目標?請注意,我無法更改表格。它的格式可能非常糟糕。

回答

0

我認爲這將做到這一點:

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 

可能需要一些調整,這取決於你使用的是什麼數據庫系統/語言。

+0

哎....我應該想到這一點。謝謝 – vikasde 2009-10-01 18:38:08