Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate nvarchar(max) to nvarchar(n) with ellipses

What's the quickest way to convert nvarchar(max) to nvarchar(n) and indicate there's more data?

eg: convert the column Address to nvarchar(100) and if Address is larger than 100 characters then replace the last 3 characters with "..."

like image 620
James Avatar asked Sep 01 '14 21:09

James


People also ask

Why is my VARCHAR Max variable getting truncated?

The reason this happens is that SQL Server doesn't want to store something as VARCHAR(MAX) if none of the variable's components are defined as VARCHAR(MAX).

Is nvarchar 4000 the same as nvarchar Max?

The answers is: there is no different between nvarchar(7) and nvarchar(4000) in term of performance & storage size. There is an interesting thing is that: if you change nvarchar(7) or nvarchar(4000) to nvarchar(max). There is a difference in term of performance & storage size. Wow, Why is this happen?

How do you truncate a character in SQL?

SQL Server TRIM() FunctionThe TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.

How do I store more than 4000 characters in SQL Server?

The storage size, in bytes, is two times the actual length of data entered + 2 bytes. The ISO synonyms for nvarchar are national char varying and national character varying. So if you specify nvarchar(max) you can store up to 1 billion 2-byte Unicode characters.


2 Answers

UPDATE t
SET t.Address = SUBSTRING(t.Address, 1, 97) + '...'
FROM TableName t
WHERE LEN(t.Address) > 100;

ALTER TABLE dbo.TableName
  ALTER COLUMN Address NVARCHAR (100);
like image 163
Tim Schmelter Avatar answered Oct 13 '22 10:10

Tim Schmelter


UPDATE Table
 SET [Address] =   CASE 
                       WHEN LEN([Address]) > 100 
                       THEN CAST([Address] AS NVARCHAR(97)) + N'...'
                       ELSE CAST([Address] AS NVARCHAR(100)) 
                   END

now change the data type of your column since all the data more than 100 characters will be truncated after the above statement.

ALTER TABLE TableName
ALTER COLUMN [Address] NVARCHAR(100)
GO
like image 38
M.Ali Avatar answered Oct 13 '22 09:10

M.Ali