Selecting a column whose name is a SQL reserved keyword

Consider the "sample_table" below

id    name   desc
-------------------------
1     kkt    kkt description
1     skt    skt description

      

desc

Is there anyway I can select the third column without using its name ?

Attempt select desc from mytable

throws an error

Please suggest.

Thank,

Balan

0


source to share


5 answers


I don't understand why you need this and I would never use it myself.

declare @T table
(
  id int,
  name varchar(10),
  description varchar(25) 
)

insert into @T values
(1,     'kkt',    'kkt description'),
(1,     'skt',    'skt description')

select T2.N.value('*[3]', 'varchar(max)')
from (select *
      from @T
      for xml path('r'), type) as T1(X)
  cross apply T1.X.nodes('/r') as T2(N)

      

Update



Instead, you should do this.

select [desc]
from YourTable

      

Use []

around column names that are reserved words.

+7


source


Use standard SQL identifiers specified in column names, which are reserved words, for example.



SELECT "desc" FROM sample_table;

      

+3


source


Does this help:

Declare @WhichOne int;
Declare @Sql varchar(200);
SET @WhichOne = 2;
WITH cte AS
(SELECT name, Row_Number() Over (ORDER BY column_id) AS rn
FROM sys.COLUMNS
WHERE Object_Name(object_id) = 'MyTable')
SELECT @Sql = 'Select ' + QuoteName(name) + ' From MyTable'
FROM cte
WHERE rn = @WhichOne;
Exec(@Sql);

      

From http://www.daniweb.com/web-development/databases/ms-sql/threads/341388

0


source


Just so you can shoot yourself in the foot, here's how you could do it with dynamic sql:

DECLARE @sql NVARCHAR(MAX)
select 
    @sql = 'SELECT ' + COLUMN_NAME + ' FROM YourTable'
from INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME='YourTable' 
AND ORDINAL_POSITION=3
exec sp_executeSQL @sql

      

0


source


select mytable.desc from mytable;

works great for me

0


source







All Articles