Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is it possible to select column data using the ordinal_position for a table column? I know using ordinal positions is a bad practice but for a one-off data import process I need to be able to use the ordinal position to get the column data.

So for example

create table Test(     Col1 int,     Col2 nvarchar(10)  ) 

instead of using

select Col2 from Test 

can I write

select "2" from Test -- for illustration purposes only 
like image 555
rams Avatar asked Dec 15 '08 14:12

rams


People also ask

What is ordinal position in SQL Server?

In relational databases, including MySQL, SQL Server, Oracle, and others, the ORDINAL_POSITION refers to a column's location in terms of ordering within a table or query output.

How do I change the ordinal position of a column in SQL Server?

In Object Explorer, right-click the table with columns you want to reorder and select Design. Select the box to the left of the column name that you want to reorder. Drag the column to another location within the table.

How do I select a specific column of data in SQL?

To select columns, choose one of the following options: Type SELECT , followed by the names of the columns in the order that you want them to appear on the report. Use commas to separate the column names.

What is column ordinal?

column ordinal [the ~] noun – A number that represents the position of the column in a set of columns. So, if a table has 3 columns, named Name, Address, and Zip, in that order, their ordinals are 0, 1, and 2. the column ordinal. – A number that represents the position of the column in a set of columns.


2 Answers

If you know quantity of columns, but don't know its names and types, you can use following trick:

select NULL as C1, NULL as C2 where 1 = 0  -- Returns empty table with predefined column names union all select * from Test  -- There should be exactly 2 columns, but names and data type doesn't matter 

As a result, you will have a table with 2 columns [C1] and [C2]. This method is not very usefull if you have 100 columns in your table, but it works well for tables with small predefined number of columns.

like image 75
Pavel Sinkevich Avatar answered Sep 21 '22 10:09

Pavel Sinkevich


You'd have to do something like

declare @col1 as varchar(128) declare @col2 as varchar(128) declare @sq1 as varchar(8000)   select @col1 = column_name from information_schema.columns where table_name = 'tablename' and ordinal_position = @position  select @col2 = column_name from information_schema.columns where table_name = 'tablename' and ordinal_position = @position2  set @sql = 'select ' + col1 ',' + col2 'from tablename'   exec(@sql) 
like image 20
Booji Boy Avatar answered Sep 22 '22 10:09

Booji Boy