SQL Query Syntax Error - Spaces in Field Names

2020-06-03 03:40发布

The database my application uses has field names containing spaces. I believe this to be the cause of my problem. Here is a typical query:

SELECT * FROM 'OV2 BAS' AS bas 
INNER JOIN 'OV2 RefID' AS ids ON 'bas.Ref ID' = 'ids.Ref ID' 
WHERE ids.ENUM_H = 'TDischarge';

How do I deal with the spaces in the field names? Thanks.

Additional Information

This is to access a database made with MS Access 2007 (Microsoft.ACE.OLEDB.12.0).

5条回答
Rolldiameter
2楼-- · 2020-06-03 04:00

Replace ' with

  • postgreSQL, Oracle: "
  • MySQL `
  • SQL-server: [ and ]

For example: "OV2 BAS", bas."Ref ID" = ids."Ref ID", etc.

查看更多
做个烂人
3楼-- · 2020-06-03 04:11

I don't think you can use quotes around the actual table name; only the name you assign to it. I would wrap the table in brackets instead: [OV2 BAS]

You also can't put quotes around your joining syntax either. Try this instead:

SELECT * FROM [OV2 BAS] AS bas INNER JOIN [OV2 RefID] AS ids ON bas.[Ref ID] = ids.[Ref ID] WHERE ids.ENUM_H = 'TDischarge';
查看更多
Bombasti
4楼-- · 2020-06-03 04:18

That depends on the database engine you're using.
For SQL Server, you have to put the field names in brackets: [ ]

SELECT * FROM [OV2 BAS] AS bas 
INNER JOIN [OV2 RefID] AS ids ON bas.[Ref ID] = ids.[Ref ID]
WHERE ids.ENUM_H = 'TDischarge';
查看更多
劳资没心,怎么记你
5楼-- · 2020-06-03 04:21

For Microsoft Access, wrap field names that contain spaces with back ticks e.g. SELECT `Eng Units` FROM Table

查看更多
Lonely孤独者°
6楼-- · 2020-06-03 04:22

You don't specify which DBMS you're using, but I'm guessing SQL server, so

SELECT *
FROM [OV2 BAS] AS bas
     ^^^^^^^^^

... enclose the field name in brackets. Using quotes as you are, turns the field name into a plain string, which will NOT be treated as a fieldname by SQL server.

查看更多
登录 后发表回答