我在一些插入T-SQL查询中见过前缀N。许多人在向表中插入值之前使用过N。
我搜索了一下,但我无法理解在向表中插入任何字符串之前包含N的目的是什么。
INSERT INTO Personnel.Employees
VALUES(N'29730', N'Philippe', N'Horsford', 20.05, 1),
这个“N”前缀有什么用途,什么时候应该使用它?
我在一些插入T-SQL查询中见过前缀N。许多人在向表中插入值之前使用过N。
我搜索了一下,但我无法理解在向表中插入任何字符串之前包含N的目的是什么。
INSERT INTO Personnel.Employees
VALUES(N'29730', N'Philippe', N'Horsford', 20.05, 1),
这个“N”前缀有什么用途,什么时候应该使用它?
它将字符串声明为nvarchar数据类型,而不是varchar
您可能已经看到Transact-SQL代码使用 N前缀。这表示后续字符串是Unicode格式的 (N实际上代表国家语言字符集)。哪一个 意味着你正在传递一个NCHAR, NVARCHAR或NTEXT值,作为 相对于CHAR, VARCHAR或TEXT。
引用微软的一句话:
前缀包含字母n的Unicode字符串常量 N前缀时,将字符串转换为默认代码页 数据库。此默认代码页可能无法识别某些字符。
如果你想知道这两种数据类型之间的区别,请参阅这篇SO文章:
varchar和nvarchar的区别是什么?
让我告诉你一件关于N'前缀的恼人的事情——我两天都没能修好它。
我的数据库排序规则是SQL_Latin1_General_CP1_CI_AS。
它有一个名为MyCol1的列的表。它是一个女巫师
此查询无法匹配存在的精确值。
SELECT TOP 1 * FROM myTable1 WHERE MyCol1 = 'ESKİ'
// 0 result
使用前缀N”可以解决这个问题
SELECT TOP 1 * FROM myTable1 WHERE MyCol1 = N'ESKİ'
// 1 result - found!!!!
为什么?因为latin1_general没有大的点İ,这就是为什么它失败了。
1. 性能:
假设你的where从句是这样的:
WHERE NAME='JON'
If the NAME column is of any type other than nvarchar or nchar, then you should not specify the N prefix. However, if the NAME column is of type nvarchar or nchar, then if you do not specify the N prefix, then 'JON' is treated as non-unicode. This means the data type of NAME column and string 'JON' are different and so SQL Server implicitly converts one operand’s type to the other. If the SQL Server converts the literal’s type to the column’s type then there is no issue, but if it does the other way then performance will get hurt because the column's index (if available) wont be used.
2. 字符集:
如果列的类型是nvarchar或nchar,那么在WHERE criteria/UPDATE/INSERT子句中指定字符串时总是使用前缀N。如果您不这样做,并且字符串中的一个字符是unicode(例如国际字符- example - ā),那么它将失败或遭受数据损坏。