开发者

SQL Server query: what is the meaning of 'N' preceding a string?

开发者 https://www.devze.com 2023-03-13 09:30 出处:网络
In SQL Server, the query SELECT custid, country, region, 开发者_如何学JAVAcity FROM Sales.Customers

In SQL Server, the query

SELECT custid, country, region, 开发者_如何学JAVAcity
FROM Sales.Customers
WHERE region = N'WA'

what is the meaning of 'N' in the where clause? I remove it, get same result.


It is casting your literal to a Unicode string.

See here for official explanation:

Unicode strings have a format similar to character strings but are preceded by an N identifier (N stands for National Language in the SQL-92 standard).

In many cases, it won't make a difference, unless your literal contains Unicode characters. If it does, and you leave out the explicit cast, it will convert your Unicode characters to a '?':

select 'Ộ', N'Ộ'

---- ----
?    Ộ


Unicode string constants that appear in code executed on the server, such as in stored procedures and triggers, must be preceded by the capital letter N. This is true even if the column being referenced is already defined as Unicode. Without the N prefix, the string is converted to the default code page of the database. This may not recognize certain characters.

For example, the stored procedure created in the previous example can be executed on the server in the following way:

EXECUTE Product_Info @name = N'Chain'

The requirement to use the N prefix applies to both string constants that originate on the server and those sent from the client.


'N' stands for National Language and denotes that you are passing a value for NVARCHAR, NCHAR. The data types that accept languages other than English start with N.

Keep in mind that you are not required to wrap your parameter with 'N' for data types like VARCHAR, CHAR because they don't accept Unicode characters.

Any other language such as Arabic, Farsi will be considered as Unicode so they should be manipulated in data types like NVARCHAR and values should be wrapped with 'N' as below:

DECLARE @Name AS NVARCHAR(50);
SET @Name = N'اسم';
PRINT @Name;

This will return:

اسم

If you try without 'N':

DECLARE @Name AS NVARCHAR(50);
SET @Name = 'اسم';
PRINT @Name;

This will return

???

It is because you haven't wrapped the value with 'N' although the data type is NVARCHAR and system doesn't know anything about the word 'اسم'.

0

精彩评论

暂无评论...
验证码 换一张
取 消