balanv balanv - 1 year ago 57
SQL Question

Selecting a column whose name is a reserved SQL keyword

Consider the below table "sample_table"

id name desc
1 kkt kkt description
1 skt skt description

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

select desc from mytable
throws an error

Please suggest.



Answer Source

I fail to see 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)


You should do like this instead.

select [desc]
from YourTable

Use [] around column names that is reserved words.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download