How to query SQL columns that have parentheses ( )

2019-07-06 18:25发布

问题:

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.

回答1:

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$]


回答2:

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.