Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a column whose name is a reserved SQL keyword

Tags:

sql

sql-server

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

like image 672
balanv Avatar asked Sep 03 '25 05:09

balanv


2 Answers

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.

like image 112
Mikael Eriksson Avatar answered Sep 04 '25 23:09

Mikael Eriksson


Use standard SQL quoted identifiers around column names that are reserved words e.g.

SELECT "desc" FROM sample_table;
like image 23
onedaywhen Avatar answered Sep 05 '25 00:09

onedaywhen