Pages

Monday, May 12, 2014

What is difference between NVARCHAR and VARCHAR datatype in SQL Server ?

What is difference between NVARCHAR and VARCHAR datatype in SQL Server ?
 

NVARCHAR :
1. Unicode Variable Length character data type. It can store both non-Unicode and Unicode (i.e. Japanese, Korean etc)
2. It takes 2 bytes per Unicode/Non-Unicode
3. If Optional parameter value n is not specified in the variable declaration or column definition then it is considered as 1.
4. When dealing with Unicode string constants in SQL Server you must precede all Unicode strings with a capital letter N.

VARCHAR :

1. Non-Unicode Variable Length character
2. It takes 1 byte per character
3. If we know that data to be stored in the column or variable doesn’t have any Unicode characters

Which one to use ?

- An nvarchar column can store any Unicode data. A varchar column is restricted to an 8-bit codepage. Some people think that varchar should be used because it takes up less space. I believe this is not the correct answer. Codepage incompatibilities are a pain, and Unicode is the cure for codepage problems. With cheap disk and memory nowadays, there is really no reason to waste time mucking around with code pages anymore.

- 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.


Example :
CREATE TABLE #t_demo 
  ( 
     mailsub1 VARCHAR(30), 
     mailsub2 NVARCHAR(30) 
  ); 
 
INSERT INTO #t_demo 
            (mailsub1, 
             mailsub2) 
VALUES      ( N'كيف حالك؟', 
                        N'كيف حالك؟');  -- N’ Indicate It’s Unicode character , If we can’t specify that then It will display ???
 
SELECT * 
FROM   #t_demo; 
 
GO 
 
DROP TABLE #t_demo;

Reference Site : 
  • http://www.codeproject.com/Articles/579523/Character-String-Data-Types-and-Functions-SQL-Serv
  • http://support.microsoft.com/kb/239530
  • http://stackoverflow.com/questions/144283/what-is-the-difference-between-varchar-and-nvarchar

No comments:

Post a Comment