简体   繁体   中英

Handling SQL reserved table and column names

Is there a way to handle reserved table & column names in your app which can work through all kinds of databases like Oracle, MySQL, SQL Server, PostGreSQL etc.

Currently, I have to do the following :

Oracle - use double quotes. MySQL - Use backtick or double quotes (depends if ANSI_QUOTES mode is enabled) SQL Server - Use brackets PostGreSQL - use double quotes.

I am aware that ANSI standard states to use double quotes but unfortunately not all dbms seem to support them.

Use double quotes. That's what the standard says, and surprisingly, it actually works on most platforms.

Require that MySQL have ANSI_QUOTES enabled, or set it at the session level :

SET SESSION sql_mode = 'ANSI'

(I used ANSI not just ANSI_QUOTES here because it makes MySQL generally a bit saner).

PostgreSQL doesn't require any special settings for identifiers (though very old versions need standard_conforming_strings = on to handle literals sensibly).

Neither does Oracle.

Modern MS-SQL shouldn't require any special settings to support double quoted identifiers :

When SET QUOTED_IDENTIFIER is ON (default), all strings delimited by double quotation marks are interpreted as object identifiers

The docs suggest that was the case in MS-SQL 2008, and if you still care about 2005 in a new application you have bigger problems.

SQLFiddles:

Interestingly, I found that the SQLFiddle for PostgreSQL failed with an odd error. I suspect an SQLFiddle bug, as it's fine on the PostgreSQL command line and via PgJDBC. It fails with there is no table that match the following pattern [with] .

All that said, if you're seriously trying to write ANSI SQL, I hope you don't plan on using:

  • Date/time maths
  • String concatenation
  • Non-trivial aggregates
  • Window functions (MySQL still doesn't support them)
  • Common table expressions
  • SQL/XML
  • Arbitrary precision decimal data types
  • Any kind of user defined procedure or function
  • Any kind of user-defined type
  • ... lots more

because different vendors use different names, have different support for features, etc.

(On a side note, if I ever meet the person who decided to call Microsoft SQL Server "SQL" in a dark alley...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM