Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a column in SQL Server with a special character in the column name?

I have a table contain the '%' in the column title, and this cause problem when I do the select statement on that column (Find below for more details). Does anyone know how can I select that column by not keeping the original column title?

Example:

Table1
name  ref_no  tot_sales  %Phone
-------------------------------
Alan  1       1          100%
amy   2       1          50%
ken   3       4          30%

Script:

Select %Phone From Table1

Error Message :

Incorrect syntax near phone

like image 361
Jin Yong Avatar asked Sep 07 '10 01:09

Jin Yong


People also ask

Can we use special characters in SQL column name?

Using special characters in column names can create a problem for the SQL queries that are used by Netcool/Impact. Netcool/Impact, in most cases, surrounds the column that contains the special characters with double quotation marks to avoid this issue. However, if the particular character is not listed in the impact.

How do you handle special characters in column names?

To use special characters in a column name, enclose the entire name in brackets ...

Which special characters are allowed in column names?

The rules for naming database objects (such as tables, columns, views, and database procedures) are as follows: Names can contain only alphanumeric characters and must begin with an alphabetic character or an underscore (_). Database names must begin with an alphabetic character, and cannot begin with an underscore.


1 Answers

You may want to wrap your column name in square brackets to have your identifier delimited:

SELECT [%Phone] FROM Table1

If the QUOTED_IDENTIFIER option is set to ON, you can also use ANSI-SQL compliant double quotation marks to delimit identifiers:

SELECT "%Phone" FROM Table1
like image 107
Daniel Vassallo Avatar answered Oct 20 '22 00:10

Daniel Vassallo