SQL Server NVARCHAR is used to store Unicode string data of variable length, it can store both Unicode and non Unicode strings.
- NVARCHAR data type is used to store Unicode string data of variable length, Can store both unicode and non-unicoden strings.
- It stores data at 2 byte per character.
- It supports up to 4000 characters.
Syntax
nvarchar(n) or nvarchar(max)
n specify the string length that ranges from 1 to 8000. Default value for n is 1.
max specify the maximum storage size which is 231-1 bytes (2 GB)
Lets Look at an example to demonstrate the properties of NVARCHAR.
Data Storage Vs Length
Here, we have a nvariable @strtxt of datatype varchar of size 30.
As varchar takes 2 bytes per character to store the data so it takes 9 bytes to store @str value ‘microsoft’ that is length of @str * 2 bytes (9 *2) =18.
It is variable-length, so it takes actual length size of string that is 9 for ‘microsoft’.
DECLARE @Str NVARCHAR(30) SET @Str = 'Microsoft' SELECT @Str AS Strtext, DATALENGTH(@Str) AS StrText_OccupiedLength , LEN(@Str) AS StrText_length
Using NVARCHAR to store Unicode Data
NVARCHAR can store Unicode data, lets try to store Hindi language text to @str variable of type NVARCHAR.
Note: Always make sure that you prefix Unicode string literals with an N prefix.
DECLARE @Str NVARCHAR(30) SET @Str = N'माइक्रोसॉफ्ट' SELECT @Str AS Strtext, DATALENGTH(@Str) AS StrText_OccupiedLength, LEN(@Str) AS StrText_length
You can see, it supports the Unicode data that you can see in the first column of result set.
Also Read..
How to get the detailed information of all datatypes in SQL Server ?