| Author |
Topic |
|
M.E.
Aged Yak Warrior
539 Posts |
Posted - 2002-10-23 : 11:48:42
|
| We have a table :Create table t1(IDKEY int,abc varchar(15),NGH varchar(15),ZOP Varchar(15))for example I have in this tableIDKEY,abc,ngh,zop1,55,66,772,33,44,55I would like the output to look likeIDKEY,ColName,ColValueso for this example I would get back1, ABC, 552, ABC, 331, NGH, 662, NGH, 441, ZOP, 772, ZOP, 55My only theory was to make a temp table and populate it asinsert into #tempselect IDKEY, 'NGH', NGHgoinsert into #tempselect IDKEY, 'ABC', ABCgoand so on...Any ideas of a way this could be automated? We've got a cursor idea... but I hate that. I think this post has been in the forums before, I'm trying to locate that post though-----------------------SQL isn't just a hobby, It's an addictionEdited by - m.e. on 10/23/2002 12:00:34 |
|
|
Page47
Master Smack Fu Yak Hacker
2878 Posts |
Posted - 2002-10-23 : 12:08:14
|
How bout...select IDKEY, 'NGH', NGH unionselect IDKEY, 'ABC', ABC unionselect IDKEY, 'ZOP', ZOPgo Jay White{0} |
 |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2002-10-23 : 12:08:37
|
| Could do a UNION:SELECT IDKey, 'abc' AS Colname, abc AS ColValue FROM t1UNION ALLSELECT IDKey, 'NGH' AS Colname, NGH AS ColValue FROM t1UNION ALLSELECT IDKey, 'ZOP' AS Colname, ZOP AS ColValue FROM t1You'll need to do some dynamic SQL if the number of columns varies. |
 |
|
|
M.E.
Aged Yak Warrior
539 Posts |
Posted - 2002-10-23 : 12:15:09
|
| Okay, thats kinda what I figured... I guess I missed part of the question. We got 6 different tables all with different numbers of columns and different column names.I've made this, but it is cursor based (stupid iterative). In @table I can put any table name and it will list the data for any table.declare @table varchar(50), @SQL varchar(5000), @col varchar(50)select @table = 'well'declare seq_cur cursorfor select column_name from information_schema.columns where table_name = @tablefor read onlyopen seq_curfetch next from seq_cur into @colwhile @@fetch_status = 0 begin select @sql = 'Select UWI, ''' + @col + ''','+@col +' from ' +@table --select @sql exec (@sql) fetch next from seq_cur into @col endclose seq_cur deallocate seq_curEdit : forgot the question... any setbased method for this? it is the truepath after all-----------------------SQL isn't just a hobby, It's an addictionEdited by - m.e. on 10/23/2002 12:15:51 |
 |
|
|
|
|
|