Use of MAX data types when over >8000 characters. (error exceeds the maximum allowed for any data type (8000).
september 18, 2013
changes/upgrades in your favorite software, become real gems at the moment you run into a problem. Like, finding out a nvarchar doesn’t go over >8000.
Since SQL2005 the keyword ‘max’ was added for the datatypes nvar, varchar and varbinary. Before the introduction of the (MAX) data types, 8000 was the absolute ‘max’, and your next best option was to use a text field, but a textfield exceeding 8000 will be handled as an out of row page and could not be used as a variable. Various of workarounds where available online, but it was never pretty.
In SQL2005 the (n)var/char data types allows variables to be as big as the (n)text datatype can be. You can do anything to them that you could with regular varchar types, but behind the scenes they function like the text data type with values less than 8000 characters in-row and values greater than 8000 characters stored in out-of-row pages. These types can be declared as local variable.
Remember, if over 8000 characters needed,Us the (MAX) data type, SQL does not allow you to use f.e. VARCHAR(10000).
What if I still want to limit the entry ?
MAX only defines more then 8000 of the character input. If you want to set a maximum of characters, like 10.000, use a CHECK CONSTRAINT To create a column of nvarchar data type with a maximum of 10.000 characters, declare the column as nvarchar (MAX) and add a check constraint to the column by checking the length of the column and making sure it is less than or equal to 10.000 characters.
CREATE TABLE [dbo].[Testdb] ( [VarChar10000] VARCHAR(MAX) )
ALTER TABLE [dbo].[Testdb] ADD CONSTRAINT [MaxLength10000]
CHECK (DATALENGTH([VarChar10000]) <= 10000)
What happpened to TEXT?
VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX) are the replacements of TEXT, NTEXT and IMAGE data types. These datatypes are deprecated after, so avoid using these data types when using < SQL Server 2005.
Wanna see some numbers?(I borrowed the calculations below from the Microsoft Knowledgebase)
The calculation for the maximum storage size for VARCHAR(MAX), NVARCHAR and VARBINARY(MAX) is 2^31-1 bytes (2,147,483,647 bytes or 2GB – 1 bytes). The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. Note: characters in an NVARCHAR data type uses two bytes, the actual maximum length for an NVARCHAR(MAX) data type is 1,073,741,822.