code_junkie

Is it possible to select sql server data using column ordinal position

Nov 12th, 2011
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. create table Test(
  2. Col1 int,
  3. Col2 nvarchar(10)
  4.  
  5. )
  6.  
  7. select Col2 from Test
  8.  
  9. select "2" from Test -- for illustration purposes only
  10.  
  11. declare @col1 as varchar(128)
  12. declare @col2 as varchar(128)
  13. declare @sq1 as varchar(8000)
  14.  
  15. select @col1 = column_name from information_schema.columns where table_name = 'tablename'
  16. and ordinal_position = @position
  17.  
  18. select @col2 = column_name from information_schema.columns where table_name = 'tablename'
  19. and ordinal_position = @position2
  20.  
  21. set @sql = 'select ' + col1 ',' + col2 'from tablename'
  22.  
  23. exec(@sql)
  24.  
  25. select table_name, column_name, ordinal_position, data_type
  26. from information_schema.columns
  27. order by 1,3
  28.  
  29. select * from information_schema.columns
  30.  
  31. declare @tmp table(field1 sql_variant, field2 int, field3 sql_variant)
  32.  
  33. insert into @tmp
  34. select * from Test
  35.  
  36. select field2 from @tmp
Add Comment
Please, Sign In to add comment