-1

I only started learning SQL less than a week ago and I have noticed in SQL Server, string can be of type nvarchar(5) or nvarchar(20) or any other number. I was just wondering what is the difference between nvarchar of different number?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Thor
  • 9,638
  • 15
  • 62
  • 137
  • 3
    Possible duplicate of [What are the main performance differences between varchar and nvarchar SQL Server data types?](http://stackoverflow.com/questions/35366/what-are-the-main-performance-differences-between-varchar-and-nvarchar-sql-serve) –  Jul 12 '16 at 04:26
  • 2
    @theinarasu at the least, the question is not about perfromances but language syntax. – clifton_h Jul 12 '16 at 04:39

2 Answers2

1

This is a declaratory statement you are referring to.

By declaratory, this is a method of declaring. MySQL has different rules depending on the context, so it is worth taking the time to know the syntax.

In SQL, such as MySQL, there are some datatypes that can be of variable length.

What you see is a declaratory statement where NVARCHAR is of different lengths.

<DATA TYPE> (<character length>)
 NVARCHAR(5) -- 5 unicode characters long.
 NVARCHAR(20) -- unicode length of 20 characters

If you do not specify a length these types of data will be one character length. So that is why the standard allows for parentheses declarations.

Examples of syntax differences:

DECLARE @string NVARCHAR(5);

SELECT CAST(<some_column> AS NVARCHAR(20)
FROM <some_table>

CREATE TABLE <schema_name>.<table_name>
( firstColumn NVARCHAR(20) NOT NULL
, secondColumn INT not null)

Like many languages, unless there is a constraint to prevent overflowing input, any insertion of a character greater than the length gets TRUNCATED...or cut off to fit inside the column.

clifton_h
  • 1,298
  • 8
  • 10
1

The number represents the content length. In a column or variable that is defined as nvarchar(5) you can put a 5 characters long unicode string. In a column or variable that is defined as nvarchar(20) you can put a 20 characters long unicode string.
This is all very basic stuff in sql, I suggest reading a good sql tutorial and come here with questions that are a little bit more advanced.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • Do you have any recommendations on a good sql book? and also, when I specify a nvarchar(5) I can still insert string length that is greater than 5, is this suppose to happen? Thank you very much for your help! – Thor Jul 12 '16 at 04:41
  • 1
    Not for a book, but you can start with w3schools sql tutorial and move on to more advanced stuff later on. If you try to insert a 20 chars length string into an `nvarchar(5)` column sql server would raise an error saying "string or binary data would be truncated". – Zohar Peled Jul 12 '16 at 04:55