Home » SQL Server NCHAR

SQL Server NCHAR

NCHAR data type is used to store Unicode string data of fixed-length.




  • NCHAR data type is used to store Unicode string data of fixed-length.
  • It stores data at 2 byte per character.
  • It supports up to 4000 characters.
Syntax
nchar(n)

n specify the string length that ranges from 1 to 4000. Default value for n is 1.

Lets Look at an example to demonstrate NCHAR data type.

Data Storage Vs Length

We have a variable @strtxt of datatype char of size 15.

DECLARE @Str NCHAR(15) 
SET @Str = 'Microsoft'
SELECT @Str AS Strtext, DATALENGTH(@Str) AS StrText_OccupiedLength ,
LEN(@Str) AS StrText_length

As nchar has fixed-length and takes 2 bytes per character to store the data so it takes 30 bytes to store @strtxt value ‘microsoft’, even though the length of @Strtxt ‘microsoft’  is 9 .

So the  data storage length of characters will be the fixed-length of variable @strtxt * 2 bytes (15 *1) =30.

Can store Unicode Data ?

NCHAR can store unicode data , again we try to store Hindi language text to @str variable of type nchar.

Note: Always make sure that you prefix Unicode string literals with an N prefix.

DECLARE @Str NCHAR(15)

SET @Str = N'माइक्रोसॉफ्ट'

SELECT @Str AS Strtext, DATALENGTH(@Str) AS StrText_OccupiedLength ,
LEN(@Str) AS StrText_length

Recommended

SQL Server VARCHAR VS NVARCHAR

SQL Server CHAR VS NCHAR




Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.