Home » excel » sql server – How to query SQL columns that have parentheses ( ) in their name?

sql server – How to query SQL columns that have parentheses ( ) in their name?

Posted by: admin April 23, 2020 Leave a comment

Questions:

The column names looks something like: “Ab. (Cd)”

It has , ‘.’ as well as ( ) in the column name.

I have tried square brackets [ ] around the column name and have also tried ‘ ‘ and ” ” without much success. Please help.

I am using SQL Server Import and Export Wizard to import some data. The query looks like:

Select 'Trans. Z4 (St 85)' from `'Monthly Prices$'`

The full SQL statement used is:

Here’s the query: Select F1, HH, AECO, Sumas, Stanfield, Malin, [PG&E], Opal, SoCal, SJ, wTX, sTX, HSC, FGTZ3, [Trans. Z4 (St 85)], Dom, [Tetco M3], 'Trans. Z6 (NY)', AGT, Dawn, Chi, Midcon from 'Monthly Prices$'

Please note that the table ‘Monthly Prices$’ is a sheet in an Excel workbook that I am trying to import.

How to&Answers:

Your query:

Select 'Trans. Z4 (St 85)' from 'Monthly Prices$'

You cannot SELECT from a string. You need to use square brackets around the table name:

Select 'Trans. Z4 (St 85)' from [Monthly Prices$]

But that’s only half of the problem. If you run this, you will get the same string, “Trans. Z4 (St 85)” on every row. You need to use square brackets for that column name as well:

Select [Trans. Z4 (St 85)] from [Monthly Prices$]

Answer:

I think it is the wizard which is your problem. Often the wizards will not have as robust an understanding of SQL as writing the statement in SSMS. I was able to create a spreadsheet with your column names but was only able to import it with the wizard if I imported the whole table not using a sql statement. Is this a possibility for you? I could query the table using brackets properly in SSMs afterwards with these names.

Answer:

To whomever next comes here for the answer, here it is:

The Excel SQL interface is terrible with column names. In your case the issue is with the dot . not the parentheses (). You must replace it with a sharp # for Excel to parse, but since it considers words with sharps in them to be (date) formatting you must also bind it with back-ticks ` or brackets [].

The correct query is:

Select 'Trans# Z4 (St 85)' from [Monthly Prices$]