В чем разница между varchar и nvarchar

What are Unicode data types

We need to convert the characters to binary so that they can be stored on a computer. To do that we need to give a binary code to all the possible characters. The ASCII (American Standard Code for Information Interchange) is the standard that defines such binary codes to represent characters.

The ASCII code uses the 7 bits for the characters and the last 8th bit is the Parity bit. The 7 bits give us 2^7 (= 128) distinct combinations. The numbers 0 to 9 were represented using the code 48 to 57 binary numbers. Similarly, A to Z (65 to 90), and a to z (97 to 122) all have a corresponding code in the ASCII table.

When it was found out that 128 characters were also insufficient, the parity bit also included raising the number of distinct combinations to 255 ( 2^8 ). The new table was called Extended ASCII code.

But, the ASCII with only 255 distinct combinations was insufficient to represent the characters from other languages. This problem was fixed using the code pages, but it was created new problems. This required a new way to encode the data. This is where Unicode comes into the picture.

The Unicode system has binary code for all the characters of all the languages of the world. Unicode is a variable bit encoding system unlike ASCII, which uses a fixed 8 bit. In Unicode, you can choose between 32, 16, or 8-bit encodings. The more bits you choose, the more languages you can support. The lower bit encodings will support a smaller subset of languages but save a lot of space.

Разница между nvarchar и varchar в базе данных!

s http-equiv=»Content-Type» content=»text/html;charset=UTF-8″>tyle=»clear:both;»>

Разница между nvarchar и varchar

Иногда при разработке полей, когда я сталкиваюсь с nvarchar и varchar, я чувствую себя немного нерешительно. Итак, давайте исследуем сегодня.

DECLARE @name AS VARCHAR (50) = 'Я тест по китайскому языку'
SELECT @name AS Name,
DATALENGTH(@name) AS 
DECLARE @nname AS NVARCHAR (50) = 'Я тест по китайскому языку'
SELECT @nname AS Name,
DATALENGTH(@nname) AS 

Максимальное значение nvarchar составляет 4000

Максимальное значение varchar составляет 8000

CREATE TABLE Test
(
  vStr varchar(10),
  nStr nvarchar(10)
)

--Для номеров
INSERT INTO . VALUES('1234567890','1234567890')

 - для писем
INSERT INTO . VALUES('abcdefghik','abcdefghik')

 --Для китайских иероглифов
 INSERT INTO .  VALUES («Я китаец», «Я китаец, я люблю свою родину»)

 --Для китайских иероглифов и букв
 INSERT INTO .  VALUES («Я китаец zz», «Я китаец Чжан»)

В общем, я предпочитаю использовать nvarchar

Некоторые люди говорят, что varchar экономит больше места, чем nvarchar, и ему следует больше использовать varchar. Но я не совсем согласен с этой точкой зрения. Во-первых, сейчас места не так не хватает, не нужно слишком запутываться с пространством. Другой момент заключается в том, что внутренний синтаксический анализ текущей операционной системы в основном кодируется в Unicode. С nvarchar вы можете избежать преобразования кодировки каждый раз, когда читаете или пишете из базы данных. Преобразование занимает много времени и легко допустить ошибки. Если что-то идет не так, восстановление не так просто, и nvarchar поддерживает несколько языков. Поэтому большую часть времени я занимаюсь проектированием баз данных с использованием nvarchar.

вперед от:https://www.cnblogs.com/gdouzz/p/7094522.html

Интеллектуальная рекомендация

1. Для реальных сигналов (для понимания): A (ω) является соотношением амплитуды выходного сигнала и амплитуды входного сигнала, называемого частотой амплитуды. Φ (ω) — это разница межд…

Один. вести Многие люди задавали некоторые вопросы о создании проекта Flex + LCDS (FDS) в сообщениях и группах. Из-за операции ее трудно четко объяснить, поэтому я написал простой учебник (я обещал эт…

package com.example.phonehttp; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.widget.ScrollView; import android.widget.TextView; public class MainActi…

Он предназначен для реализации подкласса того же родительского класса с родительским классом. Полиморфизм Один и тот же ссылочный тип использует разные экземпляры для выполнения разных операций; Идея …

тема: Объедините два упорядоченных слоя в новый заказанный список и возврат. Новый список состоит из всех узлов двух связанных списков, данных сплавным. Пример: Анализ: два связанных списка состоит в …

Вам также может понравиться

D. Самая ценная строка Пример ввода 2 2 aa aaa 2 b c Образец вывода aaa c На самом деле, будучи задетым этим вопросом, вы должны быть осторожны. После инвертирования строки, если две строки имеют один…

Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surro…

calc () может быть очень незнакомым для всех, и трудно поверить, что calc () является частью CSS. Поскольку он выглядит как функция, почему он появляется в CSS, поскольку это функция? Этот момент такж…

Основываясь на дереве регрессии, сформированном CART, а также на предварительной и последующей обрезке дерева, код выглядит следующим образом:…

Откат Обновление в режиме онлайн с версии Centos (CentOS Linux версии 7.3.1611 (Core) до CentOS Linux версии 7.5.1804 (Core)) # ошибка соединения yum-ssh после обновления yexpected key exchange group …

nvarchar(max)

nvarchar(max) is similar to nvarchar except that you can store a string of size up to 2^31-1 bytes (2 GB). The actual space occupied in the disk is the same as the size of the string in bytes + 2 bytes for length information.

nchar & nvarchar are limited to 4000 byte-pairs ( 8000 bytes ) of storage space.The SQL Server stores data in units of pages. Page size is 8 KB or 8192 bytes. Out of which 192 bytes the data is used to metadata information related to the page header, row offset, etc. That leaves us 8000 bytes to store the data. Since column data cannot exceed a page (otherwise it will be part of two pages), the maximum size you can use for a column is 8000 bytes.But in the case of nvarchar(max), the SQL server checks if the size of the string. If it is less than 8000 bytes then it stores it in the page itself. But if it is more than 8000 bytes then it moves it to a separate page known as LOB_DATA and stores the pointer in the page. In this way, nvarchar(max) columns can store data up to 2 GB.

nvarchar

nvarchar (for variable character) is a flexible width Unicode data type.

The syntax for declaring the nvarchar variable is nvarchar(n), where n defines the string size in byte-pairs. The value of n must be from 1 through 4000.

The storage taken by the nvarchar is always (2 * n) bytes + 2 bytes. The extra 2 bytes to store the length information of the string

For Example, when we store a string of length 10, The string will occupy (10*2) + 2 (=22 bytes) bytes of storage.

Unlike the nchar data type, nvarchar does not pad the string with blank spaces. Hence the data stored in the nvarchar column always occupies only the number of bytes that are needed to store the string. Hence nvarchar is more storage efficient than the nchar strings.

The number of characters that you can store in varchar(n) is n characters, if single-byte encoding character sets such as Latin (SQL_Latin1_General_CP1_CI_AS) is used, which is the default for SQL Server.

For Multibyte character sets such as Japanese or Chinese, the number of characters is less than n characters.

The following example, creates the table with two  columns.

1
2
3
4
5
6

create table nVarcharExample(

col_varchar1 nvarchar(2),

col_varchar2 nvarchar(10)

)
 

Examples

The following example show how to create nchar, nvarchar & nvarchar(max) columns.

1
2
3
4
5
6
7

create table UnicodeExample(

col_nchar       nchar(5),

col_nvarchar    nvarchar(100),

col_nvarcharMax nvarchar(max)

)
 

Inserting Values

To insert a Unicode value, you need to prefix the value with N.

1
2
3
4
5
6

create table UnicodeExample1(

colnvarchar nvarchar(100)

)
 
 

1
2
3
4
5
6
7

insert into UnicodeExample1(colnvarchar)

values(N’Unicode example in English’),

(N’यूनिकोड उदाहरण हिंदी में’),

(N’Ejemplo de Unicode en español’),

(N’中文Unicode示例’)

 

1
2
3
4
5
6
7
8

 
****Output******
 

Unicode example inEnglish

यूनिकोडउदाहरणहिंदीमें

Ejemplo de Unicode en español

中文Unicode示例
 

Without N prefix, the the string is interpreted as non Unicode. As you can see from the result both Hindi & Chinese strings are replaced with ?.

1
2
3
4
5
6
7
8
9
10
11
12

insert into UnicodeExample1(colnvarchar)

values(‘Unicode example in English’),

(‘यूनिकोड उदाहरण हिंदी में’),

(‘Ejemplo de Unicode en español’),

(‘中文Unicode示例’)

Unicode example inEnglish

?????????????????????

Ejemplo de Unicode en español

??Unicode??

 

Character count & size in bytes

In the following example, we use the Len and DATALENGTH function. The Len function returns the number of characters in a string (excluding the trailing spaces), while DATALENGTH shows the number of bytes used by that string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

 
**Create Table***
 

create table UnicodeExample3(

col_nchar    nchar(10),

col_nvarchar nvarchar(10)

)

 
***Insert Unicode string****

insert into UnicodeExample3(col_nchar,col_nvarchar)

values(N’Unicode’,N’Unicode’)

 
***Check lenth&size****

Select len(col_nchar),DATALENGTH(col_nchar),

len(col_nvarchar),DATALENGTH(col_nvarchar)

from UnicodeExample3

 
 
***Result*****

720714

 
 
 

As you can see from the result, although the number of characters is 7, the size differs. In the nchar(10) column size is 20 bytes ( 2 *10 ). While for nvarchar(10) column it is 14 (7*2).

Note that DATALENGTH does not include the additional 2 bytes, that nvarchar uses to store the data. So in disk nvarchar(10) column actually uses the 16 bytes ( i.e 7*2 + 2 bytes) to store the data.

nchar

nChar is a fixed width Unicode data type.

The syntax for declaring nchar variable is nchar(n), where n defines the string size in byte-pairs. The value of n must be from 1 through 4,000.

Note that n is string size in byte-pairs and not the number of characters or number of bytes. A byte-pair equivalent to 2 bytes.

The storage taken by the nchar is always (2 * n) bytes.

The number of characters that you can store is if the encoding is used. But if UTF-16 encoding is used, then the number of characters that you can store is less than n. This is because the Supplementary Characters in UTF-16 can take up to 4 bytes (i.e two byte-pairs).

The following example, creates the table with two columns.

1
2
3
4
5
6

create table ncharExample(

col_char1 nchar(2),

col_char2 nchar(10)

)
 

nchar Vs nvarchar

Char Varchar
Used to store a unicide string of fixed length Used to store a unicide string of variable length
The syntax is nchar(n), where n is the string size in byte-pairs (2 bytes) to use. The syntax is nvarchar(n) where n is the maximum number of string size in byte-pairs (2 bytes) to use.
If the string length is less than the size of the column then the char adds trailing spaces to the data The string is stored as it is. Does not add trailing spaces to the data
Storage size is n*2 bytes. i.e the same as the size of the column and not that of the string The Storage size is the actual size of the string + 2 bytes. The additional 2 bytes to store length information
The performance of the nchar is better than varchar. Performance is slower compared to the nchar as the SQL Server needs to calculate the size of the string
The maximum data that you can store is 4000 byte-pairs (i.e 8000 bytes) The maximum data that you can store is 4000 byte-pairs (i.e. 8000 bytes)
The number of characters you can store in a nchar(n) is n characters if a single-byte character set is used, which is the default in SQL Server The number of characters you can store in a nvarchar(n) is n characters if a single-byte character set is used, which is the default in SQL Server
A Multibyte Character Sets such as Japanese Kanji or Chinese can occupy more than 2 bytes. In such cases, the maximum storage size in bytes will remain as n. But the number of characters that can be stored may be smaller than n A Multibyte Character Sets such as Japanese Kanji or Chinese can occupy more than 2 bytes. In such cases, the maximum storage size in bytes will remain as (n*2)+2 bytes. But the number of characters that can be stored may be smaller than n
Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Все про сервера
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: