balanv balanv - 5 months ago 9
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
desc
?

Trying
select desc from mytable
throws an error

Please suggest.

Thanks,

Balan

Answer

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)

Update

You should do like this instead.

select [desc]
from YourTable

Use [] around column names that is reserved words.