NCHAR
is a fixed-sized character data type.
Use this type when values are consistent in length.
The max NCHAR
size is 4,000, storing up to 4,000 Unicode characters.
The word NCHAR
stands for national character.
Tip: Use NVARCHAR to store larger or variable-length character strings.
A table with 2 NCHAR
columns.
CREATE TABLE DemoTable
(
Id INT IDENTITY,
FirstName VARCHAR(100),
LastName VARCHAR(100),
MiddleInitial NCHAR,
Gender NCHAR(10)
);
GO
INSERT INTO DemoTable VALUES ('Harold', 'Smith', 'A', 'Male');
INSERT INTO DemoTable VALUES ('Robert', 'Johnson', 'J', 'Male');
INSERT INTO DemoTable VALUES ('Janice', 'Lopez', 'B', 'Female');
INSERT INTO DemoTable VALUES ('Kelly', 'Wilson', 'H', 'Female');
INSERT INTO DemoTable VALUES ('Grace', 'Taylor', NULL, 'Female');
GO
SELECT * FROM DemoTable;
GO
DROP TABLE DemoTable;
GO
Id | FirstName | LastName | MiddleInitial | Gender |
---|---|---|---|---|
1 | Harold | Smith | A | Male |
2 | Robert | Johnson | J | Male |
3 | Janice | Lopez | B | Female |
4 | Kelly | Wilson | H | Female |
5 | Grace | Taylor | NULL | Female |
If a value exceeds the allocated NCHAR
size, then an error will be thrown.
Syntax of NCHAR.
NCHAR(number)
number
-- optional, # of UNICODE characters (1 - 4,000). Default is 1.
ORDER |
---|
Id |
OrderDate |
OrderNumber |
CustomerId |
TotalAmount |
SELECT MONTH(OrderDate) AS Month,
'$' + CONVERT(NCHAR(9), SUM(CAST(TotalAmount AS MONEY)), 3) AS 'Total Sales'
FROM [Order]
WHERE YEAR(OrderDate) = 2013
GROUP BY MONTH(OrderDate)
ORDER BY MONTH(OrderDate)
This demonstrates a cast to a fixed length NCHAR(9)
type.
If sales exceed $100,000, an overflow error will occur.
Month | Total Sales |
---|---|
1 | $ 66,692.80 |
2 | $ 41,207.20 |
3 | $ 39,979.90 |
4 | $ 55,699.39 |
5 | $ 56,823.70 |