Reputation: 157
I have a tough programming problem in SQL Server 2000 that I'm hoping I can get help with. I am a novice with T-SQL (I mostly use MySQL) so maybe someone could look at this and see an easy way to do it.
I have a table with lots of columns that contain either a 0 or 1. For example, I have columns labeled var1, var2, var5, var9
. etc. up to about 120 columns total. Notice that the suffixes on these columns aren't necessarily consecutive. Each of these columns contain a 0 or 1. What I need to do is create a new column the contains the literal column names of every column that contains a 1.
For example, my data look like this:
ID var1 var2 var5 var7 var9
--------------------------------------
1 0 1 0 0 1
2 0 1 1 1 0
I need a new column that contains the values
ID NewCol
---------------------
1 var2,var9
2 var2,var5,var7
and so on.
For reasons I won't go in to, I can't use any client side code like VB, Perl, etc. I have to do this in a stored procedure. Due to the large number of columns that could change in either name or number, I need something other than a hardcoded series of SELECT CASE statements.
I feel really limited by my T-SQL knowledge. Can this be done??
TIA
Upvotes: 1
Views: 790
Reputation: 138960
You can do this with a query that looks like this:
select ID,
stuff(
case var1 when 1 then ',var1' else '' end +
case var2 when 1 then ',var2' else '' end +
case var5 when 1 then ',var5' else '' end +
case var7 when 1 then ',var7' else '' end +
case var9 when 1 then ',var9' else '' end
, 1, 1, '')
from YourTable
Here is a way to build it dynamically.
declare @SQL varchar(8000)
set @SQL = ''
select @SQL = @SQL + ' + case '+COLUMN_NAME+' when 1 then '','+COLUMN_NAME+''' else '''' end'
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'YourTable' and
COLUMN_NAME <> 'ID'
set @SQL = 'select ID, stuff('+stuff(@SQL, 1, 3, '')+', 1, 1, '''') from YourTable'
exec(@SQL)
Upvotes: 4