web analytics

What is the deifference between data type VARCHAR and NVARCHAR in SQL Server?

Options

codeling 1595 - 6639
@2015-12-13 10:58:28

VARCHAR and NVARCHAR are string data types of variable length in a SQL Server database.

VARCHAR

The data type NVARCHAR is used to store variable-length non-Unicode string data.

The syntax:

varchar [ ( n | max ) ]

n defines the string length and can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size is the actual length of the data entered + 2 bytes. The ISO synonyms for varchar are char varying or character varying.

 

NVARCHAR

The data type NVARCHAR is used to store variable-length Unicode string data.

The syntax:

nvarchar [ ( n | max ) ]

n defines the string length and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size, in bytes, is two times the actual length of data entered + 2 bytes. The ISO synonyms for nvarchar are national char varying and national character varying.

 

Which One Should Be Used?

In general, you should use NVARCHAR data type to define string data column or variable if you know that the data to be stored in the column or variable can have Unicode characters. 

All modern operating systems and development platforms use Unicode internally. By using nvarchar rather than varchar, you can avoid doing encoding conversions every time you read from or write to the database. Conversions take time, and are prone to errors. And recovery from conversion errors is a non-trivial problem.

@2015-12-13 11:22:11

If optional parameter n is not specified in the variable declaration or column definition

VARCHAR NVARCHAR

If optional parameter value n is not specified in the variable declaration or column definition then it is considered as 1.

Example:

DECLARE @subject VARCHAR = ‘Hello World’

SELECT @subject Subject, DATALENGTH(@subject) Length

Result:

Subject     Length
J                1

If optional parameter value n is not specified in the variable declaration or column definition then it is considered as 1.

Example:

DECLARE @subject NVARCHAR = ‘Hello World’

SELECT @subject Subject, DATALENGTH(@subject) Length

Result:
Subject       Length
J                  2

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com