BLOGS BY TOPIC
BLOGS BY AUTHOR
BLOGS BY YEAR
Whether you're creating tables in SQL Server, using SQL variables or passing parameters to stored procedures, you'll need to understand what the possible data types that you can use are.
- Data Types in T-SQL for SQL Server
- Text Data Types in T-SQL (this blog)
- Number Data Types in T-SQL
- Date and Time Data Types in SQL
- Logical, Boolean, Yes/No or Bit Data Types in SQL
- Converting between Data Types
Posted by Andy Brown on 05 October 2012
You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.
Text Data Types in T-SQL
The two things you need to decide for text are:
- Does it need to be held in Unicode format; and
- How long is it?
The latest standard of the Unicode fomrat is UTF-18; T-SQL uses the older UC-S-2 standard. The point behind Unicode is to provide a fuller set of characters. You make a data type Unicode in SQL by preceding it by an n (standing, apparently, for national character). For example:
|Normal data type||Unicode equivalent|
For normal text SQL puts aside 1 byte of storage space for each character stored; for Unicode text this figure rises to 2 bytes of storage space for each character stored.
If you're using normal text in a single language, the chances are that you won't need to hold text as Unicode characters, and can save some space.
How Long is your Text?
If you will always be holding a similar length of text in a column, parameter or variable, give it a fixed text size; otherwise, give it a variable length. Here are a couple of examples:
|Data stored||Notes on length of data||Best data type|
|UK post codes||UK post codes are either 7 or 8 characters long.||char(8)|
|UK surnames||Surnames can be double-, triple- or even quadruple-barrelled, but it's hard to imagine one longer than 100 characters.||varchar(100)|
Thus use the char data type to hold fixed-length text, and varchar to hold variable-length text.
There are also old-fashioned text and ntext data types, which Microsoft are phasing out - so avoid using these in new systems.
Putting this all Together - Text Data Types
Here then is a list of the main data text types that you can use in T-SQL:
|Data type||What it will hold|
|char, nchar||A single character, or a single Unicode character.|
|char(n), nchar(n)||A fixed-length string of n characters (where n can be any number between 1 and 8,000 for normal text or between 1 and 4,000 for Unicode text).|
|varchar(n), nvarchar(n)||A stirng of up to n characters, where n can be any number between 1 and 8,000 for normal text or between 1 and 4,000 for Unicode text.|
|varchar(MAX), nvarchar(MAX)||A string which takes up to 2,147,483,647 bytes of space (in practice, about a billion Unicode characters or 2 billion normal ones).|