Oracle 中 N'String' 与 U'String' 文字的区别

Difference between N'String' vs U'String' literals in Oracle

这些查询之间的含义和区别是什么?

SELECT U'String' FROM dual;

SELECT N'String' FROM dual;

当使用 N' 时,我们表示给定的数据类型是 NCHARNVARCHAR

U'用来表示unicode

在这个回答中我会尝试提供来自官方资源的信息

(1) N'' text Literal

N''用于将字符串转换为NCHARNVARCHAR2数据类型

根据这个 Oracle 文档 Oracle - Literals

The syntax of text literals is as follows:

where N or n specifies the literal using the national character set (NCHAR or NVARCHAR2 data).

也在这第二篇文章中Oracle - Datatypes

N'String'用于将字符串转换为NCHAR数据类型

来自上面列出的文章:

The following example compares the translated_description column of the pm.product_descriptions table with a national character set string:

SELECT translated_description FROM product_descriptions
  WHERE translated_name = N'LCD Monitor 11/PM';

(2) U'' 字面量

U'' 用于处理 Oracle 调用接口 (OCI)

中的 SQL NCHAR 字符串文字

基于此 Oracle 文档 Programming with Unicode

The Oracle Call Interface (OCI) is the lowest level API that the rest of the client-side database access products use. It provides a flexible way for C/C++ programs to access Unicode data stored in SQL CHAR and NCHAR datatypes. Using OCI, you can programmatically specify the character set (UTF-8, UTF-16, and others) for the data to be inserted or retrieved. It accesses the database through Oracle Net.

OCI is the lowest-level API for accessing a database, so it offers the best possible performance.

Handling SQL NCHAR String Literals in OCI

You can switch it on by setting the environment variable ORA_NCHAR_LITERAL_REPLACE to TRUE. You can also achieve this behavior programmatically by using the OCI_NCHAR_LITERAL_REPLACE_ON and OCI_NCHAR_LITERAL_REPLACE_OFF modes in OCIEnvCreate() and OCIEnvNlsCreate(). So, for example, OCIEnvCreate(OCI_NCHAR_LITERAL_REPLACE_ON) turns on NCHAR literal replacement, while OCIEnvCreate(OCI_NCHAR_LITERAL_REPLACE_OFF) turns it off.

[...] Note that, when the NCHAR literal replacement is turned on, OCIStmtPrepare and OCIStmtPrepare2 will transform N' literals with U' literals in the SQL text and store the resulting SQL text in the statement handle. Thus, if the application uses OCI_ATTR_STATEMENT to retrieve the SQL text from the OCI statement handle, the SQL text will return U' instead of N' as specified in the original text.


(3) 回答您的问题

从数据类型的角度来看,提供的两个查询之间没有区别

  • N'<em>string</em>'只是returns <em>string</em> 作为 NCHAR 类型。

  • U'<em>string</em>' returns 也是 NCHAR 类型,但是它确实如此对 <em>string</em> 的额外处理:它将 \ 替换为 \\<em>xxxx</em> 与 Unicode 代码点 U+<em>xxxx</em>,其中 <em> xxxx</em> 是 4 个十六进制数字。这个类似于UNISTR('<em>string</em>'),不同的是后者returns NVARCHAR2.

U' 当您想要一个独立于编码和 NLS 设置的 Unicode 字符串时,文字很有用。

示例:

select n'\€', u'\ac', n'\ac' from dual;

N'\€' U'\AC' N'\AC'
----- ---------- ----------
\€    \€         \ac