3

I have a Database table UserTable

CREATE TABLE [UserTable](
    [ID] [int] NULL,
    [Name] [nvarchar](50) NULL,
    [City] [nvarchar](50) NULL
) ON [PRIMARY]

this table have following data

ID             Name                     City
----------- --------------------------------
1             Vijendra                  Delhi
2             Singh                     Noida
3             Shakya                    New Delhi

Now question there is any way to find out the first column first row without specify the column name(I don't want to use any column name), this is same like to find out the matrix notation, that would be the [1,1]th location.

I can find out the first column first row with

Select Top 1 City from UserTable 

I don't want to user the column name(City).

Is it possible? If yes please tell me how we can achieve this.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Vijjendra
  • 24,223
  • 12
  • 60
  • 92
  • Why would you want such a thing? Columns are given names for a reason - so you could use the name in order to access them. Just using the ordinal reduces readability and for most tables, would make no sense. – Oded Oct 16 '10 at 18:48
  • @Oded:Just want to know this can we did or not. – Vijjendra Oct 16 '10 at 19:21
  • There is no "first row" either. The query `Select Top 1 City from UserTable` could perfectly legitimately return any row as you have not specified an `ORDER BY` clause. You might expect it to return the top 1 according to the `ID` order but if you add an index to the `City` column this would likely change. In neither case would any particular result be guaranteed. – Martin Smith Oct 16 '10 at 19:25
  • @Martin:Select Top 1 City from UserTable will give the first row and first column,this query I have written just for clear explanation of the question with give data and table,nothing else. – Vijjendra Oct 16 '10 at 19:39
  • "first row" as ordered by what? – Martin Smith Oct 16 '10 at 19:41

3 Answers3

0

In general, relational databases don't have a concept of an ordering of rows or columns that aren't specified by the user in a given query.

0

In quickly way you can do it by writing some code and use dynamic sql:

    declare @field varchar(100), @SQL varchar(500)
    set @field = (SELECT top 1 COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = 'UserTable')
    set @SQL = 'select top 1 ' + @field + ' from UserTable'
    exec (@SQL)

Sure may be there are more clever ways but this is a start

You can also wrap all this in stored procedure to make it more easy and readable

Hope it help

Luka Milani
  • 1,541
  • 14
  • 21
0

See sql select with column name like for choosing column names from information_schema.columns.

Also an article Perform SELECT without column names that gets columns 3, 4, and 6.

Community
  • 1
  • 1
rajah9
  • 11,645
  • 5
  • 44
  • 57